[英]Patch Request Method in Node.js and Mongoose
对于更新,我使用以下有效的代码:
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);
});
我想要做的是创建一个 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);
});
此外,我确定您可以在该行中利用 lodash,我在其中使用 for-in 循环;)
这种方法的缺点是需要对 mongo 进行 2 次查询,因为您需要一个真实的文档来比较事物。 此外,更新操作不会触发模型的后期保存挂钩。 如果您需要它们 - 您应该首先 findById(),更新必要的字段,然后在您找到的文档上点击 .save()。 希望能帮助到你
You could do this as well:
// define your middlewares here
// validateObjectId.js
const mongoose = require('mongoose');
module.exports = function (req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id))
return res.status(404).send("Invalid ID.");
next();
}
// 404.js
module.exports = function (str, id) {
if (!str || !id) throw new Error('the string name and id must be defined');
return `The ${str} with the given ID (${id}) was not found`;
}
// import your middlewares into your product route
const validateObjectId = require('../middleware/validateObjectId'); // respect your middleware path
const fourOfour = require('../middleware/404'); // respect your middleware path
router.put('/:id', validateObjectId, async (req, res) => {
const { error } = validateProduct(req.body);
const { name, description, category, tags, withdrawn, extraData, } = req.body
if (error) return res.status(400).send(error.details[0].message);
let product = await Product.findById(req.params.id).exec();
if (!product) return res.status(404).send(fourOfour("Product", req.params.id));
product = await Product.findByIdAndUpdate(req.params.id, {
name: name || product.name,
description: description || product.description,
category: category || product.category,
withdrawn: withdrawn || product.withdrawn,
extraData: extraData || product.extraData
}, { new: true });
product = await product.save();
if (!product) return res.status(404).send(fourOfour("Product", req.params.id));
res.send(product);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.