i am using expressjs(nodejs). I am trying to store array data while updating existing data ( dealtype
& dealprice
), but unable to do so.
my existing dataset
{
"_id": "56a59a2923e047bc2128cd99",
"foodImageUrl": "modules/foods/client/img/food.jpg",
"deal": [
{
"_id": "56a59a2923e047bc2128cd9a",
"dealprice": "asd",
"dealtype": "asd"
}
],
"name": "ads",
"created": "2016-01-25T03:44:41.346Z"
}
my expressjs controller
exports.update = function (req, res) {
var food = req.food;
food.name = req.body.name;
food.deal.dealtype = req.body.deal.dealtype;
food.deal.dealprice = req.body.deal.dealprice;
food.foodImageUrl = req.body.foodImageUrl;
food.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(food);
}
});
};
One way to update the existing document. First of all, find the document need to changed by _id
or other key word. here is one sample by _id
.
Food.findOne({_id: req.food._id}, function(err, food) {
food.name = req.body.name;
food.deal.dealtype = req.body.deal.dealtype;
food.deal.dealprice = req.body.deal.dealprice;
food.foodImageUrl = req.body.foodImageUrl;
food.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(food);
}
});
});
Or just use the findOneAndUpdate
to update the existing document.
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.