Mongoose Query.prototype.merge()函数
Mongoose Query API.prototype.merge() 方法 是用在查询对象上的Mongoose API中。它允许我们将一个查询与另一个查询对象合并。借助这种方法,我们可以将一个查询对象的条件,字段选择和选项与另一个查询对象合并。让我们通过一个示例来理解 merge() 方法。
语法:
query.merge( source );
参数: 该方法接受以下讨论的单个参数:
- source: 用于指定要合并的查询对象。
返回值: 该方法返回查询对象,我们可以调用回调函数。
设置Node.js应用程序:
步骤1: 使用以下命令创建Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目结构将如下所示:
数据库结构:
数据库的结构将如下所示,以下文档存在于集合中。
示例1: 在这个示例中,我们展示了merge()方法的功能,我们将sourceQuery对象合并到query对象中。
文件名: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 Customer = connectionObject.model(
"Customer",
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
})
);
const query = Customer.find();
const sourceQuery = new mongoose.Query();
sourceQuery.ne("orderNumber", 15);
query.merge(sourceQuery);
query.exec((error, result) => {
if (error) {
console.log("Error -", error);
} else {
console.log("Result -", result);
}
})
运行程序的步骤: 要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
Result - [
{
_id: new ObjectId("639ede899fdf57759087a653"),
name: 'Aditya',
address: 'Mumbai',
orderNumber: 20,
__v: 0
},
{
_id: new ObjectId("63bcfcc2876922405349b69d"),
name: 'Bhavesh',
address: 'Mhow',
orderNumber: 65,
__v: 0
}
]
示例2:
在这个示例中,我们展示了merge()方法的功能,我们将sourceQuery对象合并到query对象中。在最后,通过合并功能,条件、过滤器和选项也被合并,并且我们能够从两个查询条件中看到结果。
文件名: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 Customer = connectionObject.model(
"Customer",
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
})
);
const query = Customer.find();
query.nin('name', ["Chintu"]);
const sourceQuery = new mongoose.Query();
sourceQuery.ne("orderNumber", 65);
query.merge(sourceQuery);
query.then((res => {
console.log(res);
})).catch((err) => {
console.log(err);
})
运行程序的步骤: 从项目的根目录运行以下命令来运行应用程序:
node app.js
输出:
[
{
_id: new ObjectId("639ede899fdf57759087a653"),
name: 'Aditya',
address: 'Mumbai',
orderNumber: 20,
__v: 0
}
]
参考: https://mongoosejs.com/docs/api/query.html#query_Query-merge