问题描述
我需要查找并加入另一个集合,以从业务集合中获取业务数据以及保存在配置文件集合中的配置文件描述。最新版本的 nodejs 和 mongoose。
businesses = await Business.find({},"business_id name industry")
.limit(limit * 1)
.skip((page - 1) * limit)
.exec();
现在我在 Mongoose 中找到了 $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 一起保存在一个字段中。所以我不能使用 Mongoose 的 _id。我以前从未使用过猫鼬和两个系列。
现在的问题是配置文件[0] 未连接到正确的业务。因此,该配置文件与上述业务中的配置文件不同。
我需要找到最新的 10 家企业并加入另一个集合并掌握个人资料详细信息。我在这里做错了什么,有人有这种行为的例子吗?
解决方法
就您而言,这里没有 ObjectId,您可以使用 https://mongoosejs.com/docs/populate.html
到目前为止,您仅根据 _id 字段进行了填充。然而,这有时不是正确的选择。特别是,无限增长的数组是 MongoDB 的反模式。使用 mongoose virtuals,您可以定义文档之间更复杂的关系。
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"
});