vendredi 6 mars 2015

Mongodb - aggregate by embedded document id overwrite the outer document _id

I have this kind of 'comment' model:



{ _id: <comment-id>,
user: {
id: { type: Schema.ObjectId, ref: 'User', required: true },
name: String
},
sharedToUsers: [{ type: Schema.ObjectId, ref: 'User' }],
repliedToUsers: [{ type: Schema.ObjectId, ref: 'User' }],
}


And I want to query for all comments which pass the following conditions:



  1. sharedToUsers array is empty

  2. repliedToUsers array is empty


But also, I want the result to contain only 1 comment (the latest comment) per user by the user id.


I've tried to create this aggregate (Node.js, mongoose):



Comment.aggregate(
{ $match: { "sharedToUsers": [], "repliedToUsers": [] } },
{
$group: {
_id: "$user.id",
user: { $first: "$user" },
}
},
function (err, result) {
console.log(result);
if (!err) {
res.send(result);
} else {
res.status(500).send({err: err});
}
});


It is actually working, but the serious problem is that the results comments _id field is been overwritten by the nested user _id.


How can I keep the aggregate working but not to overwrite the original comment _id field?


Thanks


Aucun commentaire:

Enregistrer un commentaire