Mongoose-替换所有数组元素



我想替换'prices'字段中的所有数组元素,如下所示:

{
"name": "My customer name"
"taxCode":123456
"prices": 
[
{
"name": "Chocolate",
"unitPrice": 10
},
{
"name": "Cookie",
"unitPrice": 9
}
]
}

用于更改"价格"的JSON是:

{
"prices": 
[
{
"name": "Chocolate1", 
"unitPrice": 10
},
{
"name": "Candy",
"unitPrice": 5
}
]
}

这是我的代码来替换"价格"数组

router.route('/:obj/:id')
.put((req, res) => {
const PObj  = require('../models/customer');
PObj.findById(req.params.id, (err, doc) => {
if (err) { 
console.log('Lookup error: ' + err);
res.status(500).send('Error');
} else if (doc) {
doc.update({$set: req.body}, (err, task) => {
res.status(200).json(task);
});     } else {
res.status(404).send('Something is wrong');
}
});
});

代码执行完成后,但MongoDB中没有任何更改。请帮我更正代码。感谢

如果req.body打印价格数组,那么它必须是req.body.prices,而不是获取文档&更新它-这是一个双向过程,你可以试试这个:

router.route("/:obj/:id").put((req, res) => {
const PObj = require("../models/customer");
PObj.findByIdAndUpdate(
req.params.id, /** this 'req.params.id' has to be `_id` value of doc in string format */
/** internally mongoose will send this as { $set: { prices: req.body.prices }} which will replace `prices` array will new array,
*  Just in case if you wanted to push new values, have to manually do { $push: { prices: req.body.prices }} each object */
{ prices: req.body.prices },
{ new: true }, /** returns updated doc, this option is not needed if you don't need doc - by default it returns old doc */
(err, doc) => {
if (err) {
console.log("Lookup error: " + err);
res.status(500).send("Error");
} else if (doc) { 
res.status(200).json(task);
} else { /** `doc` value will be null if no doc is not found for given id */
res.status(404).send("Something is wrong");
}
}
);
});

参考:.findByIdAndUpdate((

最新更新