Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid push/addToSet null value to mongodb array

When using $push or $addToSet operator in mongoose, and the value I give (friend.id) is null or undefined, it will push a null element to the array.

dbUser.findByIdAndUpdate(
 _id,
 {
  $addToSet: {
  'friendsBlackList': friendB.id ,
  'FriendsWhiteList': friendW.id ,
  },
  },
  { new: true, upsert: true }
});

How to avoid pushing a null element? Can it be controlled in the mongoose schema? Thank you for your suggestions.

like image 888
Sulliwane Avatar asked Jul 27 '26 05:07

Sulliwane


1 Answers

I'm not familiar with Mongoose and its syntax, but what your describing can be done with the following pseudocode:

var update = { $addToSet:{}};
if(friendB.id !=null){
    update.$addToSet.friendsBlackList = friendB.id
}
if(friendW.id !=null){
    update.$addToSet.friendsWhiteList = friendW.id
}

dbUser.findByIdAndUpdate(_id,update,{ new: true, upsert: true });

Some drivers (ie Morphia) have options you can set to ignore null and empty values. You should check if Mongoose has such options as well.

like image 79
David says Reinstate Monica Avatar answered Jul 30 '26 08:07

David says Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!