我有一个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;
}
})
但没有......
答案 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
将结果发回。