我需要找到并加入另一个集合,以便从业务收集中获取业务数据和保存在概要文件集合中的配置文件描述。最新版本的nodejs和猫鼬。
businesses = await Business.find({}, "business_id name industry")
.limit(limit * 1)
.skip((page - 1) * limit)
.exec();这就是我稍后需要的代码,也是分页所需要的。
现在,我在猫鼬中找到了$Lookup的解决方案。我的代码看起来像
Business.aggregate([{
$lookup: {
from: "profiles", // collection name in db
localField: "business_id",
foreignField: "business_id",
as: "profile"
}
}]).exec(function(err, profile) {
console.log(profile[0]);
});业务和配置文件通过business_id保存在字段中。所以我不能和来自猫鼬的_id合作。我以前从没和猫鼬和两个收藏品一起工作过。
现在的问题是,配置文件没有连接到正确的业务。因此,与上面的业务发现一样,配置文件是另一个。
我需要找到最新的10个企业,并加入到另一个收集和抓取的详细资料。我在这里做错了什么,有没有人举过这种行为的例子?
发布于 2021-03-23 13:37:05
使用https://mongoosejs.com/docs/populate.html
在您的例子中,这里没有ObjectId,您可以使用人口虚拟者
到目前为止,您只基于_id字段进行了填充。然而,这有时并不是正确的选择。特别是,在没有绑定的情况下增长的数组是一个MongoDB反模式.使用猫鼬虚拟化,您可以在文档之间定义更复杂的关系。
const BusinessSchema = new Schema({
name: String
});
BusinessSchema.virtual('profile', {
ref: 'Profile', // The model to use
localField: 'business_id', // Find people where `localField`
foreignField: 'business_id', // is equal to `foreignField`
// If `justOne` is true, 'members' will be a single doc as opposed to
// an array. `justOne` is false by default.
justOne: false,
options: { sort: { name: -1 }, limit: 5 } // Query options, see "bit.ly/mongoose-query-options"
});https://stackoverflow.com/questions/66763201
复制相似问题