3

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.

4
  • 1
    Why can't you check the value of friend.id before issuing the query? Commented Nov 25, 2015 at 1:39
  • Yes, but What if there are two push operations? I updated my question Commented Nov 25, 2015 at 1:43
  • @Sulliwane You still didn't answer the question. It seems like the easiest way to do this is to check if the values you want to push are null beforehand. Commented Nov 25, 2015 at 2:44
  • @DavidGrinberg because I have two fields in the push operation, and sometimes friendB.id is null, but friendW.id is not. So even if I check the value beforehand, I cannot skip the operation (or it won't push the value that is not null). But maybe I should just split my push operations in two...so I can check value as suggested Commented Nov 25, 2015 at 2:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.