【问题标题】:MongoDB - Mongoose with NodeJS find and join collectionMongoDB - 带有 NodeJS 的 Mongoose 查找并加入集合
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 非常感谢。现在我收到错误消息 TypeError: Business.virtual is not a function
  • 谢谢。我检查了所有内容,不存在将被覆盖的变量。我已经创建了类似 const Business = mongoose.model('Business', new mongoose.Schema({ ... and exports.Business = Business; 的架构;有问题吗?
  • 好的,我已经解决了这个问题。但在我对 mongoose 的 find 声明中,人口仍然没有配置文件字段可见。
  • 也修复了这个问题。由 circleSchema.set('toObject', { virtuals: true }); 解决circleSchema.set('toJSON', { virtuals: true });
猜你喜欢
  • 2018-08-21
  • 2019-08-01
  • 1970-01-01
  • 2021-12-11
  • 2021-08-23
  • 1970-01-01
  • 2014-04-13
  • 2019-08-07
  • 2018-12-28
相关资源
最近更新 更多