我想爲在貓鼬中找到的每個文檔添加一個額外的屬性state: 'found'
。我有以下代碼:如何使用貓鼬將其他屬性添加到mongoDB中查找文檔?
router.get('/all', function(req, res, next) {
var allPets = [];
FoundPet.find({}, function(err, pets) {
pets = pets.map((obj) => {
obj.state = 'found';
return obj;
})
res.send(pets)
})
});
我期待有這樣的事返回:
[
{
"_id": "59c7be569a01ca347006350d",
"finderId": "59c79570c5362d19e4e64a64",
"type": "bird",
"color": "brown",
"__v": 0,
"timestamp": 1506291998948,
"gallery": [],
"state": "found" // the added property
},
{
"_id": "59c7c1b55b25781b1c9b3fae",
"finderId": "59c79a579685a91498bddee5",
"type": "rodent",
"color": "brown",
"__v": 0,
"timestamp": 1506291998951,
"gallery": [],
"state": "found" // the added property
}
]
,但我不能讓新的屬性添加成功使用上面的代碼,有沒有什麼解決辦法爲了那個原因 ?
你不需要使用'陣列#map'這裏,使用'陣列#forEach'代替。 – alexmac
@alexmac,是!還有一些錯誤處理必須完成,但這取決於OP。 –