【问题标题】:Updating DB Shema in Express JS with Mongoose library使用 Mongoose 库更新 Express JS 中的 DB Schema
【发布时间】:2020-02-03 04:25:51
【问题描述】:

我在 Express.js 中使用 Mongoose 创建了一个 Mongo DB 模式,并且正在构建 REST API。但是,当我尝试更新现有记录时,我未从架构更新的值会自动变为空。我理解为什么会发生这种情况,只是不确定应该如何编码。

这是路线:

router.patch("/:projectId", async (req, res) => {
  try {
    const updatedProject = await Project.updateOne(
      { _id: req.params.projectId },
      {
        $set: {
          title: req.body.title,
          project_alias: req.body.project_alias,
          description: req.body.description
        }
      }
    );
    res.json(updatedProject);
  } catch (err) {
    res.json({ message: err });
  }
});

这里也是架构:

const ProjectsSchema = mongoose.Schema({
  title: {
    type: String,
    required: true,
    unique: true
  },
  project_alias: {
    type: String,
    unique: true,
    required: true
  },
  description: String,
  allowed_hours: Number,
  hours_recorded: {
    type: Number,
    default: 0
  },
  date_added: {
    type: Date,
    default: Date.now
  }
});

我的问题是当我只想更新标题时:

{
    "title" : "Title Updated33"
}

描述和别名变为空。我应该实施检查吗?

【问题讨论】:

    标签: node.js mongodb rest express mongoose


    【解决方案1】:

    只需将 req.body 用于更新对象,如下所示:

    router.patch("/:projectId", async (req, res) => {
    
      try {
        const updatedProject = await Project.updateOne(
          { _id: req.params.projectId },
          req.body
        );
        res.json(updatedProject);
      } catch (err) {
        res.json({ message: err });
      }
    });
    

    或者更好的是,创建一个像这样的辅助函数,以便我们可以排除模型中不存在的正文中的字段:

    const filterObj = (obj, ...allowedFields) => {
      const newObj = {};
      Object.keys(obj).forEach(el => {
        if (allowedFields.includes(el)) newObj[el] = obj[el];
      });
      return newObj;
    };
    
    router.patch("/:projectId", async (req, res) => {
      const filteredBody = filterObj(
        req.body,
        "title",
        "project_alias",
        "description",
        "allowed_hours",
        "hours_recorded"
      );
    
      try {
        const updatedProject = await Project.updateOne(
          { _id: req.params.projectId },
          filteredBody
        );
        res.json(updatedProject);
      } catch (err) {
        res.json({ message: err });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 2020-09-15
      • 2017-10-17
      • 2021-08-09
      • 2018-12-30
      • 2019-06-25
      • 2016-02-15
      • 2017-08-12
      • 2021-09-09
      相关资源
      最近更新 更多