如何仅更新MongoDB数据库中对象的某些属性 [英] How to update only some properties of object in MongoDB database

查看:561
本文介绍了如何仅更新MongoDB数据库中对象的某些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的代码不允许API用户通过传递一个请求属性来仅更新一个字段.我可以在userObj处删除null,但是UI开发人员将不得不从数据库传递现有数据来进行更新,这不是最佳实践.

My code below doesn't allow the API user to update only one field by passing one request property. I can remove the null at userObj, but the UI developer will have to pass existing data from the database to do an update, which is not the best practice.

这是我的Express路线:

Here is my Express route:

router.put('/user', (req, res) => {
  const userObj = {
    name: req.body.name || null,
    location: {
      city: req.body.city || null
      },
      phone: req.body.phone || null
    };

  User.updateUser(req.body.id, userObj)
});

这是我的猫鼬模型的updateUser函数:

Here is my Mongoose model's updateUser function:

module.exports.updateUser = (_id, userObj, callback) => {
  User.findOneAndUpdate({_id}, userObj, { upsert: true, 'new': true }, callback);
}

推荐答案

首先,要解决仅更新某些特定属性的问题,您必须使用

First, to address your issue with updating only a few certain properties, you have to use the $set operator to set only a certain field. When you pass userObj directly to findOneAndUpdate you reset the whole object thus you have to pass all the existing properties. Use $set:

User.findOneAndUpdate({_id}, { $set: userObj }, { upsert: true, new: true }, callback);

这只会将userObj中定义的属性更新为它们的新值,而不会触碰其他任何东西.同样,您可以在这种用例中使用findByIdAndUpdate:

This will update only the properties defined in userObj to their new values and touch nothing else. Also, you could just use findByIdAndUpdate for this very use-case:

User.findByIdAndUpdate(_id, { $set: userObj }, { upsert: true, new: true }, callback);

接下来,您不应该使用PUT.使用补丁. PUT意味着将资源放在某个URL上,如果资源已经存在,则将其完全替换. PATCH意味着您仅更新资源的一些属性,并且确实替换了整个属性.这不会影响应用程序的功能,但这是一个巨大的语义问题和最终用户问题,正如他们期望的那样.

Next, you shouldn't be using PUT. Use PATCH. PUT implies putting a resource at some URL, and replacing it entirely if it already exists. PATCH means you update only a few properties of a resource, and does replace the whole thing. This won't affect the app's functionality, but it's a huge semantics issue and end-user issue as they'd expect PATCH.

这篇关于如何仅更新MongoDB数据库中对象的某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆