Home > Software engineering >  How to catch the value that is $pull in mongoose?
How to catch the value that is $pull in mongoose?

Time:08-31

What im trying to do is to catch the value that is pulled from the user model.

_id:630e2a2250283de03b2dc920
phone:" 4567..."
createdAt:2022-08-30T15:17:54.608 00:00
selectedClients:Array
 0: phone: " 1234..."
    fullName: "John"
    _id: 630e2a8f8367a2aaac3343b4
    createdAt: 2022-08-30T15:19:43.372 00:00
__v:0

So to remove "John" from selectedClients I do this:

exports.remove = asyncHandler(async (req, res, next) => {
  const user_id = req.params.user_id.split("-")[1];
  const client_id = req.params.client_id.split("-")[1];

  const removeTrustee = await User.findOneAndUpdate(
     { _id: user_id },
     { $pull: { selectedClient: { _id: client_id } } },
     { multi: true }
   );

So how can I catch the value that is removed in a variable or how can I find it before its pulled from the database ?

CodePudding user response:

What you could do is retrieve the deleted client before deletion:

exports.remove = asyncHandler(async (req, res, next) => {
  const user_id = req.params.user_id.split('-')[1];
  const client_id = req.params.client_id.split('-')[1];

  const user = await User.findOne({
    _id: user_id,
    'selectedClients._id': client_id,
  });
  if (user.selectedClients.length > 0) {
    // Retrieve the pulled value (if present) before deletion
    const selectedClient = user.selectedClients[0];
  }

  // Delete the element from the list
  user.selectedClients.pull({ _id: client_id })
  await user.save();
});
  • Related