首页 > 解决方案 > 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 家企业并加入另一个集合,并获取个人资料详细信息。我在这里做错了什么,有没有人有这种行为的例子?

标签: node.jsmongodbmongoosemongoose-schemamongoose-populate

解决方案


使用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"
});

推荐阅读