【发布时间】:2021-06-20 02:38:53
【问题描述】:
我需要找到并加入另一个集合以从企业集合中获取企业数据以及保存在配置文件集合中的配置文件描述。最新版本的 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。我以前从未使用过 mongoose 和两个系列。
现在的问题是配置文件[0] 未连接到正确的业务。因此,该配置文件是上面业务中的另一个配置文件。
我需要找到最新的 10 家企业并加入另一个集合并获取个人资料详细信息。我在这里做错了什么,有没有人有这种行为的例子?
【问题讨论】:
-
谢谢@TusharGupta-curioustushar 看起来不错,但我怎么能在这里使用business_id 作为匹配字段而不是Schema.Types.ObjectId
标签: node.js mongodb mongoose mongoose-schema mongoose-populate