S
S
Stanislav2018-01-26 12:21:54
MongoDB
Stanislav, 2018-01-26 12:21:54

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 }
    }]
}

The goal is simple, to get comments and assign data from the users collection to each owner, that's what I WANT to get:
{
    comments: [{
        owner: {
             _id: 'User ID',
             avatar: 'user avatar'
        },
        post: 'текст комментария',
        createdAt: 'тут дата создания коммента'
    }]
}

I'm trying to do so
Posts.aggregate([
    { $match: { url: 'url-url' } },
    {
        $lookup: {
            from: 'users',
            localField: 'comments.owner',
            foreignField: '_id',
            as: 'comments.owner'
        }
    }, {
        $project: {
            _id: 1,
            comments: 1
        }
    }
]).....

The output is not what I need
"comments":{  
   "owner":[  
      {  
         "_id":"54ad4806f273e66f2bfa6984",
         "username":"username",
         "avatar":"54ad4806f273e66f2bfa6984.jpg",
         "createdAt":"2013-06-16T22:11:37.000Z"
      }
   ]
}

How to build a query correctly?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question