不确定如何返回端点

时间:2017-09-17 06:45:57

标签: node.js express mongoose

我有一个Node / Express API,我不知道如何返回$ group的结果。

我的代码:

router.route('/viewed_card/:invite_id')
    .get(function(req, res){
     Profile.aggregate([
            {$unwind:'$contacts'},
            {$unwind:'$contacts.shared'},
            {$match:{'contacts.shared.invite_id':req.params.invite_id}},
            {$group:{
                _id:null,
                first_name:{$first:'$contacts.first_name'},
                last_name:{$first:'$contacts.last_name'}
            }}
        ])

    })

如何返回结果?

我尝试在“Profile.aggregate”函数之前进行“返回”。

我可能会这样:

router.route('/viewed_card/:invite_id')
    .get(function(req, res){
     Profile.aggregate([
            {$unwind:'$contacts'},
            {$unwind:'$contacts.shared'},
            {$match:{'contacts.shared.invite_id':req.params.invite_id}},
            {$group:{
                _id:null,
                first_name:{$first:'$contacts.first_name'},
                last_name:{$first:'$contacts.last_name'}
            }}
        ], function(err, result){
            return result;
        }

    })

但没有......

2 个答案:

答案 0 :(得分:1)

如果我没有错,聚合会返回promise,你可以尝试这种方式

var profile=Profile.aggregate([
    {$unwind:'$contacts'},
    {$unwind:'$contacts.shared'},
    {$match:{'contacts.shared.invite_id':req.params.invite_id}},
    {$group:{
        _id:null,
        first_name:{$first:'$contacts.first_name'},
        last_name:{$first:'$contacts.last_name'}
    }}
]);

profile.then((data) => {
    res.status(200).jsonp({
        data
    });
})
.catch(err => {
    res.status(422).jsonp({errors: err});
}); 

或者您可以使用cursor

之类的内容
Profile.aggregate([
    {$unwind:'$contacts'},
    {$unwind:'$contacts.shared'},
    {$match:{'contacts.shared.invite_id':req.params.invite_id}},
    {$group:{
        _id:null,
        first_name:{$first:'$contacts.first_name'},
        last_name:{$first:'$contacts.last_name'}
    }}
]).toArray(function(err, results) {
    if(!err) res.status(200).jsonp(ageNodes);
    else res.status(422).jsonp(err);
});

答案 1 :(得分:0)

将您关注的数据发送回响应res对象。

您在function(req, res) {},您有一个请求req对象和一个响应res对象。您正在从req中提取信息以获取姓名。使用res将结果发回。