问题
How can I update a MongoDB document with Mongoose when only a subset of its fields are specified? (i.e. update the specified fields, but leave any other existing fields unchanged)
In the following route handler, the user can choose which fields to provide. The following works, but using the if statements does not feel particularly great. Is there a more elegant solution?
// Get the user properties from the request body
const { email, firstname, lastname} = req.body;
// Decide what fields to update
const fieldsToUpdate = {
updatedAt: Date.now(),
};
if(email) fieldsToUpdate.email = email;
if(firstname) fieldsToUpdate.firstname = firstname;
if(lastname) fieldsToUpdate.lastname = lastname;
// Update the user object in the db
const userUpdated = await User
.findByIdAndUpdate(
userId,
fieldsToUpdate,
{
new: true,
runValidators: true,
}
);
I have tried a different approach using email: email but if a field is undefined or null, Mongoose will put null in the database instead of leaving the field unchanged?
回答1:
You can create a helper method like this:
const filterObj = (obj, ...allowedFields) => {
const newObj = {};
Object.keys(obj).forEach(el => {
if (allowedFields.includes(el) && (typeof obj[el] === "boolean" || obj[el]))
newObj[el] = obj[el];
});
return newObj;
};
And use it like this:
let filteredBody = filterObj(req.body, "email", "firstname", "lastname");
filteredBody.updatedAt = Date.now();
// Update the user object in the db
const userUpdated = await User.findByIdAndUpdate(userId, filteredBody, {
new: true,
runValidators: true
});
来源:https://stackoverflow.com/questions/59093772/update-subset-of-fields-with-mongoose