【问题标题】:Mongoose aggregate with $in带有 $in 的 Mongoose 聚合
【发布时间】:2017-11-27 09:26:41
【问题描述】:

在阅读https://stackoverflow.com/a/44688386/2802552 之后,我该如何在我的情况下应用它?

[UserSchema]
name : String

[ConversationSchema]
participants : [User]

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

我试图通过一个查询获得对话列表及其消息,仅在用户属于Conversation.participants 的情况下。

感谢您的帮助。

【问题讨论】:

    标签: node.js mongoose nosql


    【解决方案1】:

    使用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 :)  
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-04
      • 2021-08-23
      • 2019-06-22
      • 2021-05-15
      • 2019-08-01
      • 2021-09-13
      • 2018-01-30
      • 2014-02-19
      相关资源
      最近更新 更多