Here is an schema of my collection "profile":
{
_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"}
]
}
I want to $push an embedded array:
{
_id : new ObjectID(), rate : 60.0, raisedOn : "7/5/2012"
}
and return this after execution.
So I made this thru mongoose,
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);
It was good that the returned value (which is the whole object) is:
{
_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"}
]
}
But my aim was to return only the value:
{_id : ObjectId("65009be546"), rate : 60.0, raisedOn : "7/5/2012"}
and not the whole document.
How should I do it? What did i missed in this line:
dbmodel.findOneAndUpdate(condition, { $push: { defaultrates: insert } }, options, callback);
Seen as you are getting the full updated object back (due to the { new: true }
option), you can locate the last element in the embedded document array using JavaScript and send that as your response.
So with this object...
{
_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"}
]
}
You can do this...
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
}
Hopefully this will help someone that comes across this thread.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.