简体   繁体   English

猫鼬独特并填充文档

[英]mongoose distinct and populate with documents

I have the following model:我有以下模型:

var followerSchema = new Schema({
    id_follower: {type: Schema.Types.ObjectId, ref: 'Users'},
    id_post: {type: Schema.Types.ObjectId, ref: 'Posts'}
});

I want to be able to find all posts for a list of followers.我希望能够找到关注者列表的所有帖子。 When I use find, it returns me of course multiple times the same post as multiple users can follow the same post.当我使用 find 时,它当然会多次返回同一个帖子,因为多个用户可以关注同一个帖子。

So I tried to use distinct, but I have the feeling the "populate" does not work afterwards.所以我尝试使用不同的,但我觉得“填充”之后不起作用。

Here is my code:这是我的代码:

followerModel
    .distinct('id_post',{id_follower:{$in:followerIds}})
    .populate('id_post')
    .sort({'id_post.creationDate':1})
    .exec(function (err, postFollowers) {
        console.log(postFollowers);
    })

It only returns me the array of the posts, and it is not populated.它只返回我的帖子数组,并且没有填充。

I am new to mongoDB, but according to the documentation of mongoose, the "distinct" method should return a query, just as the "find" method.我是 mongoDB 的新手,但根据 mongoose 的文档,“distinct”方法应该返回一个查询,就像“find”方法一样。 And on a query you can execute the "populate" method, so I don't see what I am doing wrong.在查询中,您可以执行“populate”方法,所以我看不出我做错了什么。

I also tried to use the .distinct() method of the query, so then my code was like this:我也尝试使用查询的 .distinct() 方法,所以我的代码是这样的:

followerModel
    .find({id_follower:{$in:followerIds}})
    .populate('id_post')
    .distinct('id_post')
    .sort({'id_post.creationDate':1})
    .exec(function (err, postFollowers) {
        console.log(postFollowers);
    })

In that case it works, but as in the documentation of mongoose you need to provide a callback function when you use the distinct method on a query, and so in my logs I get errors all over.在那种情况下它可以工作,但是在 mongoose 的文档中,当您对查询使用不同的方法时,您需要提供回调函数,因此在我的日志中,我到处都是错误。 A workaround would be to have a dummy callback function, but I want to avoid that...一种解决方法是使用虚拟回调函数,但我想避免这种情况......

Does anybody has an idea why the first attempt is not working?有没有人知道为什么第一次尝试不起作用? And if the second approach is acceptable by providing a dummy callback?如果通过提供虚拟回调可以接受第二种方法?

Would this be the right way considering the current lack of support in mongoose?考虑到猫鼬目前缺乏支持,这是正确的方法吗?

followerModel
.find({id_follower:{$in:followerIds}})
.distinct('id_post',function(error,ids) {
   Posts.find({'_id':{$in : ids}},function(err,result) {
     console.log(result);
   });
});

You can simply use aggregate to group and populate the collection.您可以简单地使用聚合来分组和填充集合。 now we have the desired result现在我们有了想要的结果

db.<your collection name>.aggregate([
  {
    $match: {<match your fields here>}
  },
  {
    $group: {_id: <your field to group the collection>}
  },
  {
    $lookup: {
              from: "<your collection of the poupulated field  or referenced field>",
              localField: "<give the id of the field which yout want to populate from the collection you matched above cases>",
              foreignField: "_id", //this references the id of the document to match the localField id in the from collection
              
              as: 'arrayName', //<some name to the returned document, this is a single document array>
            }
  },
  {
    $project: {
     //you really don't want the whole populated fields, you can select the fields you want
     <field name>: 
<1 or 0>, // 1 to select and 0 to not select 
     //you can add multiple fields here 
     //to select the fields that just returned from the last stage we can use
     "arrayName._id": <1 or 0>,
      }
  }
])
//at last you can return the data
.then((data) =>{
  console.log(data);
});

we have distinct() by $group and populate() by $lookup and we also select() by $project我们有distinct() by $grouppopulate() by $lookup我们也select() by $project

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM