mongodb group参考$ project

时间:2015-11-15 12:51:08

标签: node.js mongoose aggregate-functions

你好我不明白为什么,组后没有参考值 查询执行无错误

我希望在访问其他值模型的引用时赶上消息ID和用户对象

我的架构

comments: {
    user: { // <---reference users PROBLEM
        type: mongoose.Schema.Types.ObjectId,
        ref: 'users'
    },
    message: {// <---reference messages PROBLEM
        type: mongoose.Schema.Types.ObjectId,
        ref: 'messages'
    },
    text: {type: String, required: true},
    created_at: { type: Date,  "default": Date.now}
}

我的查询

 db.getCollection('comments').aggregate([
            {$match: {'message': ObjectId("564854b1b7eb16fb511d90c0")}},
            {
                $group: {
                    _id: '$user',
                     count: {$sum: 1},
                     author: {$last: '$user'},
                     messages_test: {$last: '$text'},
                     msg_id: {$last: '$message._id'}
                },
            },
            {
                $project: {
                     count : 1,
                     messages_test : 1,
                     msg_id : 1,
                     username: { $concat: [ "$author.name", " ", "$author.surname" ] } 
                }   
            },  
        ]);`

结果查询(空参考值)问题

{
"result" : [ 
    {
        "_id" : ObjectId("563f2db0e2bf6c431b297d45"),
        "count" : 3.0000000000000000,
        "messages_test" : "x",
        "msg_id" : null, //<-------EMPTY
        "username" : null//<-------EMPTY
    }, 
    {
        "_id" : ObjectId("563f7c0a8db7963420cd5732"),
        "count" : 3.0000000000000000,
        "messages_test" : "333",
        "msg_id" : null,//<-------EMPTY
        "username" : null//<-------EMPTY
    }
], 

}

预期结果

{
"result" : [ 
    {
        "_id" : ObjectId("563f2db0e2bf6c431b297d45"),
        "count" : 3,
        "messages_test" : "x",
        "msg_id" : "563f2db0e2bf6c431b2asd5", //<-------NOT EMPTY
        "username" : "John Travolta"//<-------NOT EMPTY
    }, 
    {
        "_id" : ObjectId("563f7c0a8db7963420cd5732"),
        "count" : 4,
        "messages_test" : "333",
        "msg_id" : "563f2db0e2bf6c431b2jgk6",//<-----NOT EMPTY
        "username" : "Bill Gates"//<-------NOT EMPTY
    }
], 

}

事实是,当我是结构子文档时,我是在

的帮助下完成的
message.aggregate([
            {$match: {_id: mongoose.Types.ObjectId(id)}},
            {$unwind: "$comments"},
            {
                $group: {
                    _id: '$comments.user_id',
                    count: {$sum: 1},
                    author: {$last: '$comments.username'},
                    messages_test: {$last: '$comments.text'},
                    msg_id: {$last: '$_id'}
                }
            }
        ],
        function (err, msg) { ...

并且一切都恢复了,但在这种结构中,我无法应对这样的任务 click

我想如何做一些普遍的请求,但我不知道如何

请帮助我

0 个答案:

没有答案