node.js - MongoDB - 带有 NodeJS 的 Mongoose 查找并加入集合
问题描述
我需要找到并加入另一个集合以从业务集合中获取业务数据以及保存在配置文件集合中的配置文件描述。最新版本的 nodejs 和猫鼬。
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 家企业并加入另一个集合,并获取个人资料详细信息。我在这里做错了什么,有没有人有这种行为的例子?
解决方案
使用https://mongoosejs.com/docs/populate.html
在您的情况下,您在这里没有 ObjectId,您可以使用populate-virtuals
到目前为止,您只根据 _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"
});
推荐阅读
- javascript - redux item reducer的异步函数中的返回语句不改变状态
- nginx - Nginx 允许特定的 ip4 地址
- c++ - 如何设置我的构造函数以使头部和尾部指向一个哨兵?(在 C++ 中的单链表中)
- perl - 如何直接取消引用存储在另一个哈希中的哈希引用?
- asp.net-mvc - 如何在同一个解决方案中使用 Web API?
- oop - 我应该为每个不同的构造函数创建类还是应该只为一个类创建两个构造函数?
- python-3.x - 从具有多个条件的 Pandas 数据帧执行计算
- replace - How to create list of files containing only filename in one set_fact task
- postgresql - 将 JSON.RawMessage 转换为 JSON
- hdl - HDL - PC.hdl 但从 x2 8 位寄存器开始