gpt4 book ai didi

node.js - 如何在填充mongodb后进行过滤

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:56 24 4
gpt4 key购买 nike

我需要根据服务类型过滤我的业务文档。

var BusinessSchema = Schema({
name: String,
slug: String,
service: [{type: Schema.ObjectId, ref: 'Service'}],
owner: {type: Schema.ObjectId, ref: 'User'}

});

module.exports = mongoose.model('Business', BusinessSchema);

架构服务是:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ServiceSchema = Schema({
name: String,
});

module.exports = mongoose.model('Service', ServiceSchema);

在这一系列企业中,只需要那些在其服务中包含“服务 A”的企业。

"business": [
{
"_id": "594957df4e195d2500324726",
"owner": "59482e80d4df7208503154b8",
"slug": "Almacene2s",
"name": "Almacene2s",
"__v": 0,
"service": [
{
"_id": "594ab160778ae82c44af3a78",
"name": "Service C",
"__v": 0
},
{
"_id": "594ab1be778ae82c44af3a7a",
"name": "Service D",
"__v": 0
}
],

},
{
"_id": "5948483e6bcc1f2788b09145",
"owner": "59482e80d4df7208503154b8",
"slug": "guaranda-2",
"name": "Guaranda Fig",

"service": [
{
"_id": "594ab160778ae82c44af3a78",
"name": "Service A",
"__v": 0
},
{
"_id": "594ab1be778ae82c44af3a7a",
"name": "Service B",
"__v": 0
}
],

}
]

在这种情况下我想要得到的结果是:

{
"_id": "5948483e6bcc1f2788b09145",
"owner": "59482e80d4df7208503154b8",
"slug": "guaranda-2",
"name": "Guaranda Fig",

"service": [
{
"_id": "594ab160778ae82c44af3a78",
"name": "Service A",
"__v": 0
},
{
"_id": "594ab1be778ae82c44af3a7a",
"name": "Service B",
"__v": 0
}
],

}

能够执行此搜索对我来说非常重要,因为系统将允许用户选择具有所需服务的企业作为过滤器。

这是我在 Nodejs + mongodb 上的第一个项目,在继续之前我希望得到您的帮助。非常感谢

最佳答案

使用$lookup ,这是您可以实现的目标:

Service.aggregate([
{
$match: {
"name": "Service A"
}
},
{
$lookup: {
from: "business",
localField: "_id",
foreignField: "service",
as: "businesses"
}
}
], function(err, result) {
console.log(result);
});

在此聚合管道中,您首先匹配并查找名称为“Service A”的服务文档。然后在 service 业务文档数组中查找匹配的文档,并将它们放入 businesses 字段中。结果将如下所示:

{
"_id" : "594af96883ab76db8ecd021b",
"name" : "Service A",
"businesses" : [
{
"_id" : "594af9a683ab76db8ecd0225",
"slug" : "Almacene2s",
"owner" : "59482e80d4df7208503154b8",
"name" : "Almacene2s",
"service" : [
"594af96883ab76db8ecd021b",
"594af96883ab76db8ecd021d"
]
}
]
}

关于node.js - 如何在填充mongodb后进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44686945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com