MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Aggiorna il sottoinsieme di campi con Mongoose

Puoi creare un metodo di supporto come questo:

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;
};

E usalo in questo modo:

  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
  });