Reputation: 40444
session document:
{
"_id" : ObjectId("5648b811a16bc2e0355b8289"),
"title" : "test",
"messages" : [
{
"authorId" : ObjectId("5648b89f2fc311bc39073993"), // <-- the users id
"created" : ISODate("2015-11-15T16:51:29.652Z"),
"message" : "<p>test</p>"
}
]
}
user document:
"_id" : ObjectId("5648b89f2fc311bc39073993"),
"pic" : "karl.png",
"profile" : {
"name" : "Karl Morrison"
}
first query:
var id = '5648b811a16bc2e0355b8289'; // <-- id for the session document
var session = // <-- returns the session document
yield sessions.findOne({
_id: id,
});
second query (this is where I am stuck):
var sessionUsers =
yield new Promise(function (resolve, reject) {
users.col.aggregate([
{
$match: {
'_id': {
'$in': session.messages.authorId // <--- here I need help! Need all of the authorId's in the session document from the previous query result.
}
}
},
{
$project: {
_id: 1,
pic: 1,
name: '$profile.name'
}
}
],
function (err, res) {
if (err === null)
resolve(res);
reject(err);
});
});
So I am trying to get all of the authorId
's into an array and feed that array into the $in
of the second query, which should return an array full of elements with the fields of _id
, pic
and name
.
So sessionUsers
variable should look something like this:
[{
"_id" : ObjectId("5648b89f2fc311bc39073993"),
"pic" : "karl.png",
"name" : "Karl Morrison"
},...]
Upvotes: 1
Views: 510
Reputation: 5354
I am not sure if I understand the problem correctly, but I think you are trying to send an array of objects instead of an array of _id's behind your $match
. You will need to get all _id
's in a simple array and use the result. You can use lodash. Here are the docs for more information.
The code below "plucks" all _id's from your session data.
var ids = _.pluck(session.messages, 'authorId');
Next, change the $match
part to this:
{
$match: {
'_id': {
'$in': ids
}
}
}
Upvotes: 1