【问题标题】:Mongoose Populate and Search by Array of ReferencesMongoose 按引用数组填充和搜索
【发布时间】:2016-05-31 05:22:45
【问题描述】:

我正试图围绕 Mongoose Populate 语法和结构展开思考。我有两个模式。 Parent 有一个 Child 引用数组。

const Parent = new Schema({
  name: String,
  children: [{type: Schema.ObjectId, ref: 'Child'}]
});

const Child = new Schema({
  name: String
});

为了填充 Parent 我一直在这样做:

Parent
  .findById(parent.id)
  .populate('children')
    .exec( (err, parent) => {
      parent.children = arrayOfInsertedChildDocs;
      parent.save();
    });

Parent 引用保存,但有没有办法查询具有某个 Child 引用的 Parents?例如,所有在其 children 数组中引用 ID 为 ObjectId('xxxxxxxxx') 的孩子的父母?

这是我一直在尝试的,但它不起作用。

let query = { "children._id": mongoose.Types.ObjectId(childId) };

Parent.find(query, (err, parents) => {
   //process parents 
}) 

这可能吗?

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query mongoose-populate


    【解决方案1】:

    想通了。从嵌套数组中的子 id 获取 Parent 的查询是:

    Parent
      .find({"children":ObjectId(child.id)})
      .populate("children")
      .exec((err,parents) => {
        //process parents
      });
    

    【讨论】:

      【解决方案2】:

      您想在 MongoDB 数组集中搜索元素。假设您有一个文档。

      {
        name :"harry",
        childen:["10ahhdj20","9ajskjakj9","8aiisu38","2jjaksjah0"]
      }
      

      所以要在数组列表中搜索,你可以使用这个。

      db.parents.find( { tags: { $all: [ "10ahhdj20", "812922dd" ] } } )
      

      你会得到所有有这些孩子的父母。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-01
        • 2019-01-31
        • 2022-12-12
        • 2017-05-07
        • 2020-11-03
        • 2014-12-05
        • 2019-07-28
        • 2022-06-14
        相关资源
        最近更新 更多