Gia*_*nis 3 mongoose mongodb node.js express
对于更新,我使用以下有效的代码:
router.put('/:id', async (req, res) => {
const { error } = validateProduct(req.body);
if (error) return res.status(400).send(error.details[0].message);
const product = await Product.findByIdAndUpdate(req.params.id,
{
name: req.body.name,
description: req.body.description,
category: req.body.category,
tags: req.body.tags,
withdrawn: req.body.withdrawn,
extraData: {
brand: req.body.extraData.brand,
quantity: req.body.extraData.quantity,
type: req.body.extraData.type
}
},
{new: true}
);
if (!product) return res.status(404).send('The product with the given ID was not found.');
res.send(product);
});
Run Code Online (Sandbox Code Playgroud)
我想要做的是创建一个 Patch 操作,它只更新某些字段,而不是像上面的更新那样更新所有字段。这些字段不是标准字段,但它们是更新操作的上述字段之一。
你可以试试这个片段(虽然没有在本地测试它)。这个想法是只更新产品中的那些字段,这些字段在 req.body 中提到过。确保你的验证器是安全的,否则你最终会被 nosql 注入。
router.put('/:id', async (req, res) => {
const { error } = validateProduct(req.body);
if (error) return res.status(400).send(error.details[0].message);
const product = await Product.findById(req.params.id).exec();
if (!product) return res.status(404).send('The product with the given ID was not found.');
let query = {$set: {}};
for (let key in req.body) {
if (product[key] && product[key] !== req.body[key]) // if the field we have in req.body exists, we're gonna update it
query.$set[key] = req.body[key];
const updatedProduct = await Product.updateOne({_id: req.params.id}, query}).exec();
res.send(product);
});
Run Code Online (Sandbox Code Playgroud)
此外,我确定您可以在该行中利用 lodash,我在其中使用 for-in 循环;)
这种方法的缺点是需要对 mongo 进行 2 次查询,因为您需要一个真实的文档来比较事物。此外,更新操作不会触发模型的后期保存挂钩。如果您需要它们 - 您应该首先 findById(),更新必要的字段,然后在您找到的文档上点击 .save()。希望能帮助到你
| 归档时间: |
|
| 查看次数: |
7297 次 |
| 最近记录: |