Update subset of fields with Mongoose

本小妞迷上赌 提交于 2020-01-22 02:29:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!