📌  相关文章
📜  Query.prototype.j() 如何在Mongoose中工作?

📅  最后修改于: 2022-05-13 01:56:31.820000             🧑  作者: Mango

Query.prototype.j() 如何在Mongoose中工作?

Query.prototype.j()函数用于请求确认该操作已被持久化到 MongoDB 的磁盘日志中。

句法:

Query.prototype.j()

参数:此函数有一个布尔类型的 val 参数。
返回值:此函数返回查询对象。
安装mongoose:

npm install mongoose

安装mongoose模块后,您可以使用命令在命令提示符下检查您的mongoose版本。

npm mongoose --version

之后,您可以创建一个文件夹并添加一个文件,例如 index.js,如下所示。

数据库:这里使用的示例数据库如下所示:

示例 1:
文件名:index.js

javascript
const mongoose = require('mongoose');
  
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.updateOne({name:"Gourav"}, { $set: {name: 'Geek'} }).j(true);
console.log("Above operation has been persisted to MongoDB's on-disk journal")


javascript
const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.updateOne({name:"Gourav"}, { $set: {name: 'Geek'} }).j(false);
console.log("Above operation has not been persisted to MongoDB's on-disk journal")
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});


项目结构将如下所示:

使用以下命令运行index.js文件:

node index.js

输出:

Above operation has been persisted to MongoDB's on-disk journal

示例 2:
文件名:index.js

javascript

const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.updateOne({name:"Gourav"}, { $set: {name: 'Geek'} }).j(false);
console.log("Above operation has not been persisted to MongoDB's on-disk journal")
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});

项目结构将如下所示:

使用以下命令运行index.js文件:

node index.js

输出:

Server listening on PORT 3000
Above operation has not been persisted to MongoDB's on-disk journal

参考:
https://mongoosejs.com/docs/api/query.html#query_Query-j