Mongoose aggregate with $in

adaba

after reading https://stackoverflow.com/a/44688386/2802552 how can I apply it in my case ?

[UserSchema]
name : String

[ConversationSchema]
participants : [User]

[MessageSchema]
sender : User
conversation : Conversation
content : String

I am trying to get with one query a list of conversations and its messages ONLY where the user is part of Conversation.participants.

Thanks for your help.

adaba

Using async.waterfall :

async.waterfall([
    function (cb) {
        Conversation.aggregate([
            {
                $lookup: {
                    from: Message.collection.name, // collection name in db, mongo uses plural in $lookup (nice trick preventing from "hard-coding" it)
                    localField: '_id',
                    foreignField: 'conversation',
                    as: 'messages'
                }
            },
            {
                $project: {
                    'messages.conversation': 0 // to hide the conversation id in Conversation.messages array
                }
            }
        ], function (err, conversations) {
            cb(null, results);
        });
    },
    function (results, cb) {
        Conversation.populate(conversations, [{
                path: 'participants',
                model: 'User',
                select: 'name'
            }, {
                path: 'messages.sender',
                model: 'User',
                select: 'name'
            }], function (err, results) {
                cb(null, results)
            }
        )
    }], function (err, results) {
    console.log(results); // finally :)  
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive