繁体   English   中英

更新 mongodb 上的某些字段并非全部。 如何?

[英]update some field on mongodb not all. How?

我仍在学习 Node.js 和 MongoDB 所以我的问题是:更新功能想要更新一些不需要的字段那么我该怎么做?

注意:我使用相同的 validateTask function 将新数据插入任务文档。

 router.put('/:id', (req, res) => { const { error } = validateTask(req.body); if(error) return res.status(400).send(error.details[0].message); Task.findByIdAndUpdate(req.params.id, { name: req.body.name, employee: req.body.employee, description: req.body.description, section: req.body.section, status: req.body.status, updated_at: new Date() }, { new: true }).then ( data => { res.status(201).send(data); }).catch(err => { res.status(422).send('The task with given ID was not found'); }); }); function validateTask(task) { const schema = { name: Joi.string().min(3).required(), employee: Joi.string().min(3).required(), description: Joi.string().min(3).required(), section: Joi.string().min(3).required(), status: Joi.boolean() }; return Joi.validate(task, schema); }

为此,您可以使用 Task.findByIdAndUpdate 它只会更新您提供的字段,例如

User: {
  name: Ahmed Gamal
  email: ahmed@ahmedgamal.ga
  country: Egypt 
}

当与 findByIdAndUpdate 一起使用并给定{name: Ahmed}时,结果将是

User: {
  name: Ahmed
  email: ahmed@ahmedgamal.ga
  country: Egypt 
}

移除 validateTask 验证

该错误是因为在 validateTask function 中,您已按要求填写所有字段,并且在 findByIdAndUpdate 之前验证了这些参数。

我相信您不需要在更新中完成任何必需的(必填字段)验证。 只能对新插入的文档进行此验证

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM