In my project Node and Mongo project, i'm using mongoose for my modelling. I'm trying to perform a lookup on a nested document. I have a thread object, with an array of "post" objects as one of its properties. One of the properties of this nested "post" object, is a user_id, the person who posted. I've tried to lookup the user_id(ie - localfield: thread.post.user_id, from users, foreignfield: _id) but the shell keeps returning nothing.
Can anybody suggest an amendment to what i've tried below:
db.threads.aggregate([
{ "$match": { "posts._id": ObjectId("abcdef") } },
{ "$sort": { "dateAdded": -1 } },
{ "$limit": 15 },
{ "$lookup": {"localField": "posts.user_id","from": "users","foreignField": "_id","as": "userinfo"} },
{ "$unwind": "$userinfo" },
{ "$project":{"dateAdded":1,"userinfo.name":1,"userinfo.username":1}}
]);
And a sample of the records in my collections
db.threads.find({}) returns...
{
"_id" : ObjectId("78910"),
"dateAdded" : ISODate("2017-08-18T16:44:23Z"),
"title" : "Thread Zero",
"posts" : [ {
"_id" : ObjectId("abcdef"),
"user_id" : ObjectId("12345"),
"postText" : "good evening",
"dateAdded" : "2017-8-18 17:44:34" } ],
"__v" : 0
}
db.users.find({}) returns...
Sample user object
{
"_id" : ObjectId("12345"), "name" : "James Free",
"name" : "Al Isonwunderland",
"password" : "$2a$10$ILpitvg1.o8X8GnaSaoG4ulnuNWrFTUfhQDA8CdihbHPjBrB8NaVm",
"username" : "muppet",
"__v" : 0
}
So from this, I would like to return the name property from the "user" object for each of the posts on the thread. What i've written is an attempt to get the user's name ad username for one specific post, I would assume retrieving the user name and name for all comments is to leave the $match parameter blank, allowing it to return a list of posts along with the user's name/username
Can anyone confirm this?