[英]Mongoose - findOneAndUpdate dynamically $push into array
[英]Mongoose findOneAndUpdate return only the newly $push document
這是我的收藏“個人資料”的架構:
{
_id : ObjectId("2bb0fad110"),
name : "Tommy",
defaultrates :
[
{_id : ObjectId("444cbcfd52"), rate : 35.0, raisedOn : "5/2/2009"},
{_id : ObjectId("2e642b1510"), rate : 55.0, raisedOn : "5/3/2010"},
{_id : ObjectId("47cc4d69d3"), rate : 65.0, raisedOn : "5/5/2010"}
]
}
我想 $push 一個嵌入式數組:
{
_id : new ObjectID(), rate : 60.0, raisedOn : "7/5/2012"
}
並在執行后返回。
所以我通過貓鼬做了這個,
var condition = { '_id': "2bb0fad110"},
insert = {
'_id': new ObjectID(),
'rate': 60.0,
'raisedOn': "7/5/2012",
},
options = { strict: false, new: true };
function callback (err, result) {
if (err) { console.log(err); res.status(400).send("error"); }
console.log('result:' + JSON.stringify(result));
res.json(result);
}
dbmodel.findOneAndUpdate(condition, { $push: { defaultrates: insert } }, options, callback);
返回值(即整個對象)是:
{
_id : ObjectId("2bb0fad110"),
name : "Tommy",
defaultrates :
[
{_id : ObjectId("444cbcfd52"), rate : 35.0, raisedOn : "5/2/2009"},
{_id : ObjectId("2e642b1510"), rate : 55.0, raisedOn : "5/3/2010"},
{_id : ObjectId("47cc4d69d3"), rate : 65.0, raisedOn : "5/5/2010"},
{_id : ObjectId("65009be546"), rate : 60.0, raisedOn : "7/5/2012"}
]
}
但我的目標是只返回值:
{_id : ObjectId("65009be546"), rate : 60.0, raisedOn : "7/5/2012"}
而不是整個文檔。
我應該怎么做? 我在這一行中錯過了什么:
dbmodel.findOneAndUpdate(condition, { $push: { defaultrates: insert } }, options, callback);
當您正在獲取完整更新的對象時(由於{ new: true }
選項),您可以使用 JavaScript 定位嵌入式文檔數組中的最后一個元素並將其作為響應發送。
所以有了這個對象...
{
_id : ObjectId("2bb0fad110"),
name : "Tommy",
defaultrates :
[
{_id : ObjectId("444cbcfd52"), rate : 35.0, raisedOn : "5/2/2009"},
{_id : ObjectId("2e642b1510"), rate : 55.0, raisedOn : "5/3/2010"},
{_id : ObjectId("47cc4d69d3"), rate : 65.0, raisedOn : "5/5/2010"},
{_id : ObjectId("65009be546"), rate : 60.0, raisedOn : "7/5/2012"}
]
}
你可以這樣做...
function callback (err, result) {
if (err) { console.log(err); res.status(400).send("error"); }
console.log('result:' + JSON.stringify(result));
// BELOW ADDED
const newDefaultRate = result.defaultrates[result.defaultrates.length - 1]; // gets the last element in the array
res.status(201).json(newDefaultRate); // http status 201 to show new resource created
}
希望這會幫助遇到此線程的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.