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.
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)
});
Here is my Mongoose model's updateUser function:
module.exports.updateUser = (_id, userObj, callback) => {
User.findOneAndUpdate({_id}, userObj, { upsert: true, 'new': true }, callback);
}