Querying after populate in Mongoose

后端 未结 6 2145
悲&欢浪女
悲&欢浪女 2020-11-21 16:17

I\'m pretty new to Mongoose and MongoDB in general so I\'m having a difficult time figuring out if something like this is possible:

Item = new Schema({
             


        
6条回答
  •  星月不相逢
    2020-11-21 16:39

    After having the same problem myself recently, I've come up with the following solution:

    First, find all ItemTags where tagName is either 'funny' or 'politics' and return an array of ItemTag _ids.

    Then, find Items which contain all ItemTag _ids in the tags array

    ItemTag
      .find({ tagName : { $in : ['funny','politics'] } })
      .lean()
      .distinct('_id')
      .exec((err, itemTagIds) => {
         if (err) { console.error(err); }
         Item.find({ tag: { $all: itemTagIds} }, (err, items) => {
            console.log(items); // Items filtered by tagName
         });
      });
    

提交回复
热议问题