Mongoose Aggregation匹配一个objectIds数组

我有一个模式,看起来像这样

var Post = new mongoose.Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, created: { type: Date, Default: Date.now }) 

我也有一个用户表。 我有一个用户ID的数组,我试图search基于用户ID数组的post表

例如

 var userIds = ["575e96652473d2ab0ac51c1e","575e96652473d2ab0ac51c1d"] .... and so on 

我想返回这些用户创build的所有post。 post应该按创builddatesorting。 有没有办法根据提供的用户ID分组这个职位,基本上匹配个人用户的职位?

我试图达到的结果是这样的:

  [{ userAId : "56656.....", post : [postA, postB], },{ userBId :"12345...", post : [postA, postB] }] 

我如何编写这个查询?

这是我迄今为止

 Post.aggregate([{ // {"$unwind" : ""}, // "$group": { // _id: "$author", // "created" : {"$sum" : 1 } // } "$match" : { author : id} }]).exec(function(error, data) { if(error){ return console.log(error); }else{ return console.log(data) } }) { "_id" : ObjectId("575e95bc2473d2ab0ac51c1b"), "lastMod" : ISODate("2016-06-13T11:15:08.950Z"), "author" : ObjectId("575dac62ec13010678fe41cd"), "created" : ISODate("2016-06-13T11:15:08.947Z"), "type" : "photo", "end" : null, "commentCount" : 0, "viewCount" : 0, "likes" : 0, "tags" : [], "title" : "Today is a good day", "__v" : 0 } 

要返回由ID列表中描述的用户创build的所有post,请在查询中使用$in运算符,然后将sort()方法链接到查询以按创build的date字段sorting结果:

 Post.find({ "author": { "$in": userIds } }) .sort("-created") // or .sort({ field: 'asc', created: -1 }); .exec(function (err, data){ if(error){ return console.log(error); } else { return console.log(data); } }); 

为了在每个用户拥有postID的情况下获得结果,您需要运行以下聚合操作:

 Post.aggregate([ { "$match:" { "author": { "$in": userIds } } }, { "$sort": { "created": -1 } }, { "$group": { "_id": "$author", "posts": { "$push": "$_id" } } }, { "$project": { "_id": 0, "userId": "$_id", "posts": 1 } } ]).exec(function (err, result){ if(error){ return console.log(error); } else { return console.log(result); } }); 

或者stream利的API:

  Post.aggregate() .match({ "author": { "$in": userIds } }) .sort("-created") .group({ "_id": "$author", "posts": { "$push": "$_id" } }) .project({ "_id": 0, "userId": "$_id", "posts": 1 }) .exec(function (err, result){ if(error){ return console.log(error); } else { return console.log(result); } }); 

这应该是可能的,没有聚合。

 Post .find({ author: { $in: userIds } }) .sort({ created: -1 }) 

如果您得到CastError:Cast to ObjectId失败,请确保将您的userIds数组从string数组映射到mongooseid的数组。

userIds = userIds.map(userId => new mongoose.Types.ObjectId(userId))