【问题标题】:How to update single value of document in Nodejs and mongo db如何在 Node Js 和 mongodb 中更新文档的单个值
【发布时间】:2021-09-11 10:28:19
【问题描述】:

嘿,我是 nodeJS 的新手。我一直在更新单个文档实体。我正在轻松更新整个文档,但无法更新单个值。 代码

router.patch("/:id", async (req, res) => {
  console.log(req.params.id);
  // check valid student
  let student = await Student.findById(req.params.id);
  if (!student) return res.status(400).send("Student Not Found");

  // validition
  // const { error } = validate(req.body);
  // if (error) return res.status(400).send(error.details[0].message);

  // update the student
  student = await Student.updateOne({_id:req.params.id},{$set: req.body});
  if(!student) return res.status(404).send('The student record not Updated')
  res.status(200).send('Student Record Updated')
});

验证函数

function validateStudent(student){
    const schema = Joi.object({
        name:Joi.string().min(3).max(50).required(),
        fatherName:Joi.string().min(3).max(50).required(),
        email:Joi.string().min(5).max(50).required().email(),
        class:Joi.number().min(9).max(12).required(),
        fee:Joi.number().min(4000).max(10000).required(),
        address:Joi.string().min(1).max(255).required(),
        phone:Joi.string().min(1).max(255).required(),
    })
    return schema.validate(student)
}

现在它正在更新我在 DB 中的单个值,但没有验证,因为如果我取消注释验证,那么它会强制所有必填字段。如何验证和更新从前端传入 API 的单个值?

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    更新单个字段,如电子邮件

    student = await Student.updateOne({_id:req.params.id},{$set: {email: req.body.email});
    

    但是..

    如果加班,这可能是一项艰巨的任务

    • 您打算在所有 API 中使用建议的方法。
    • 或者如果模型具有多个字段名称并且您正在选择性地更新。

    我建议继续使用您现有的方法,只要

    • req.body 始终包含文档中的所有现有数据
    • 不包含有用的字段,例如 createdAtupdatedAt 其他可能会更新的字段..

    为了反驳第二点,您可以使用 Joi 验证来禁止未知字段。

    Source

    【讨论】:

      【解决方案2】:

      请试试这个

        student = await Student.updateOne({_id:req.params.id},req.body);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-07
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        相关资源
        最近更新 更多