[英]How to update only some properties of object in MongoDB database
My code below doesn't allow the API user to update only one field by passing one request property. 我下面的代码不允许API用户通过传递一个请求属性来仅更新一个字段。 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. 我可以在userObj
处删除null,但是UI开发人员将必须从数据库传递现有数据来进行更新,这不是最佳实践。
Here is my Express route: 这是我的Express路线:
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)
});
Here is my Mongoose model's updateUser
function: 这是我的猫鼬模型的updateUser
函数:
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. 首先,要解决仅更新一些特定属性的问题,您必须使用$set
运算符仅设置特定字段。 When you pass userObj
directly to findOneAndUpdate
you reset the whole object thus you have to pass all the existing properties. 当你通过userObj
直接findOneAndUpdate
您重置整个对象因此你必须通过所有现有的属性。 Use $set
: 使用$set
:
User.findOneAndUpdate({_id}, { $set: userObj }, { upsert: true, new: true }, callback);
This will update only the properties defined in userObj
to their new values and touch nothing else. 这只会将userObj
定义的属性更新为它们的新值,并且什么也别碰。 Also, you could just use findByIdAndUpdate
for this very use-case: 同样,您可以针对以下用例使用findByIdAndUpdate
:
User.findByIdAndUpdate(_id, { $set: userObj }, { upsert: true, new: true }, callback);
Next, you shouldn't be using PUT. 接下来,您不应该使用PUT。 Use PATCH. 使用补丁。 PUT implies putting a resource at some URL, and replacing it entirely if it already exists. PUT意味着将资源放在某个URL上,如果资源已经存在,则将其完全替换。 PATCH means you update only a few properties of a resource, and does replace the whole thing. PATCH意味着您仅更新资源的一些属性,并且确实替换了整个属性。 This won't affect the app's functionality, but it's a huge semantics issue and end-user issue as they'd expect PATCH. 这不会影响应用程序的功能,但这是一个巨大的语义问题和最终用户问题,因为他们期望PATCH。
使用$ set
User.findOneAndUpdate({_id}, {$set: userObj}, /* ... */)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.