I'm setting up a function that searches for a user based on an id and if no user is found, it creates a new one. I have no users yet so the query never returns a user. However, I'm unable to successfully check for this case. What exactly is returned when a find query is empty?
 User.find(id,(error,user)=>{
        if(error){
          console.log(error);
        }else{
          if(user == [] || user == null || user == undefined || user == {} || user == '[]'){
            User.addUser({"fbID":id,"lastMessage":"[]"},(error,response)=>{
              if(error){
                console.log(error);
              }else{
                console.log(response);
              }
            });
          }else{
            console.log("User exists.");
          }
        }
      });
                and it will return array? find returns an array always.
Does mongoose query returns Promise? Mongoose queries are not promises. They have a . then() function for co and async/await as a convenience.
exec() function returns a promise, that you can use it with then() or async/await to execute a query on a model "asynchronous".
First let's consider your conditions:
user == [] || user == null || user == undefined || user == {} || user == '[]'
user == [] will always be false. Even [] == [] is always false.user == null then you don't need user == undefined and vice versa because null == undefined is always true (unlike null === undefined which is not).user == {} will always be false. Even {} == {} is always false.user == '[]' can be true if user literally contains the string [] but this will never happen in MongoHere is how to check if there was anything found or not:
For User.find:
User.find({}, (err, users) => {
  // users is an array which may be empty for no results
  if (err) {
    // handle error
    return;
  }
  if (users.length) {
    // there are user(s)
  } else {
    // there are no users
  }
});
For User.findOne:
User.findOne({}, (err, user) => {
  // user is a single document which may be null for no results
  if (err) {
    // handle error
    return;
  }
  if (user) {
    // there is user
  } else {
    // there is no user
  }
});
For User.findById:
User.findById(id, (err, user) => {
  // user is a single document which may be null for no results
  if (err) {
    // handle error
    return;
  }
  if (user) {
    // there is user
  } else {
    // there is no user
  }
});
                        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