H
H
HitGirl2021-11-12 21:13:51
MongoDB
HitGirl, 2021-11-12 21:13:51

How to do a lookup based on the result of a lookup?

Hello!
Can you please tell me how to get the user's login for each message? (highlighted line)

return RoomModel.aggregate().match({ "users": new mongoose.Types.ObjectId(userId)})
        .lookup({ from: 'users', localField: 'owner', foreignField: '_id', as: 'owner' }).unwind({path:"$owner"})
        .lookup({ from: 'users', localField: 'users', foreignField: '_id', as: 'users' })
        .lookup({from: 'roommessages', localField: '_id',foreignField: 'room', as: 'messages'  })
       .lookup({ from: 'users', localField: 'messages.author', foreignField: '_id', as: '$messages.author' })
        .addFields({messages: {$filter: {input: '$messages', as: 'item', cond: {$in: [new mongoose.Types.ObjectId(userId), '$$item.recipients' ]}}}})
        .project({ _id:0,name:1,"password": { $ne: [ "$password", "empty" ] }, "owner.login":1, "users.login":1,
            "messages.message":1, "messages.author": 1,
        });


Line
.lookup({ from: 'users', localField: 'messages.author', foreignField: '_id', as: '$messages.author' })

doesn't work as it should.

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