我有一个对象数组,我想要做的只是返回_id和personalInfo但是将它们组合成一个
这是我的示例数组:
[
{
"_id": "57c4085234b1ccad0e7780f8",
"personalInfo": {
"firstName": "Ryan",
"middleName": "sadsada",
"lastName": "Tan",
"nickname": "dsada",
},
"deleted": false,
"updatedAt": "2016-08-29T10:02:58.900Z",
"createdAt": "2016-08-29T10:02:58.900Z",
}
]
到目前为止,我所做的是:
Patient.find({
'deleted' : false
}, 'personalInfo', function (err, patients) {
if (err) {
return res.send(err);
}
res.send(patients);
});
它给我一个结果:
[
{
"_id": "57c4085234b1ccad0e7780f8",
"personalInfo": {
"firstName": "Ryan",
"middleName": "sadsada",
"lastName": "Tan",
"nickname": "dsada"
}
}
]
我想要的是它应该返回像这样的对象数组
[
{
"_id": "57c4085234b1ccad0e7780f8",
"firstName": "Ryan",
"middleName": "sadsada",
"lastName": "Tan",
"nickname": "dsada"
}
]
我通过使用lodash迭代数组来解决这个问题,以获得我想要的预期结果。是否有一种猫鼬类的方式,我不必手动迭代值,以给我相同的结果?
答案 0 :(得分:0)
它不可能在猫鼬中...你必须在查询结果中映射你的数据..你可以使用lodash或非核心的libary来轻松地映射你的数据
var _ = require('lodash');
Patient.find({
'deleted': false
}, 'personalInfo', function(err, patients) {
if (err) {
return res.send(err);
}
var finalData = _.map(patients, function(obj) {
return {
"_id": obj._id,
"firstName": obj.personalInfo.firstName,
"middleName": obj.personalInfo.middleName,
"lastName": obj.personalInfo.lastName
}
});
res.send(finalData);
});