如何仅更新MongoDB数据库中对象的某些属性 [英] How to update only some properties of object in MongoDB database
问题描述
我下面的代码不允许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屋!