Answer the question
In order to leave comments, you need to log in
What is the correct way to apply lookup to an array of objects?
I’m doing something wrong, because at the output I get only one object with user data and that’s it.
There is a collection with posts in which there is a field with comments, here is the document structure (mongoose schema)
{
url: { type: String },
comments: [{
owner: { type: mongoose.Schema.Types.ObjectId, ref: 'Users', required: !0 },
post: { type: String, trim: !0, required: !0 },
public: { type: Number, default: 0 },
createdAt: { type: Date, default: Date.now }
}]
}
{
comments: [{
owner: {
_id: 'User ID',
avatar: 'user avatar'
},
post: 'текст комментария',
createdAt: 'тут дата создания коммента'
}]
}
Posts.aggregate([
{ $match: { url: 'url-url' } },
{
$lookup: {
from: 'users',
localField: 'comments.owner',
foreignField: '_id',
as: 'comments.owner'
}
}, {
$project: {
_id: 1,
comments: 1
}
}
]).....
"comments":{
"owner":[
{
"_id":"54ad4806f273e66f2bfa6984",
"username":"username",
"avatar":"54ad4806f273e66f2bfa6984.jpg",
"createdAt":"2013-06-16T22:11:37.000Z"
}
]
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question