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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With