Mongoose Query.prototype.setOptions()函数
Mongoose的 Query API.prototype.setOptions() 方法是用在查询对象上的。它允许我们为方法设置要执行的查询选项。某些操作仅适用于特定的方法。让我们通过一个示例来理解 setOptions() 方法。
语法:
query.setOptions( object );
参数:
此方法接受一个单一参数,具体描述如下:
- object: 用于指定查询条件的对象。
返回值:
此方法返回查询对象,我们可以在其上调用回调函数。
设置 Node.js Mongoose 模块:
步骤1:
使用下面的命令创建一个 Node.js 应用:
npm init
步骤2: 在创建 NodeJS 应用程序之后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目结构将如下所示:
数据库结构:
数据库的结构将如下所示,以下是在MongoDB中存在的数据库。
示例1: 下面的示例演示了 Mongoose Connection setOptions() 方法的基本功能。在这个示例中,我们根据 rollNumber 字段按升序对结果集进行排序。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String },
age: { type: Number },
rollNumber: { type: Number },
});
const Student = connectionObject.model(
'Student', studentSchema
);
const query = Student.find();
query.setOptions({ sort: { rollNumber: 1 } })
query.then(result => {
console.log(result);
})
运行程序的步骤:
要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
[
{
_id: new ObjectId("63a40a1065e8951038a391b1"),
name: 'Student1',
age: 30,
rollNumber: 9,
__v: 0
},
{
_id: new ObjectId("63a4a9a207370cdcd1961b2c"),
name: 'Student2',
age: 18,
rollNumber: 176,
__v: 0
},
{
_id: new ObjectId("63a4a98407370cdcd1961b1a"),
name: 'Student3',
age: 33,
rollNumber: 178,
__v: 0
}
]
示例2: 下面的示例演示了Mongoose Connection setOptions()方法的基本功能。在这个示例中,我们跳过了结果集中的前2个记录。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String },
age: { type: Number },
rollNumber: { type: Number },
});
const Student = connectionObject.model(
'Student', studentSchema
);
const query = Student.find();
query.setOptions({ skip: 2 })
query.exec((error, result) => {
if (error) {
console.log(error);
} else {
console.log(result)
}
})
运行程序的步骤:
要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
[
{
_id: new ObjectId("63a4a9a207370cdcd1961b2c"),
name: 'Student2',
age: 18,
rollNumber: 176,
__v: 0
}
]
参考: https://mongoosejs.com/docs/api/query.html#query_Query-setOptions