Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does mongoose return when a find query is empty?

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.");
          }
        }
      });
like image 658
Patrick Connors Avatar asked Jul 18 '17 16:07

Patrick Connors


People also ask

Does find return an array mongoose?

and it will return array? find returns an array always.

Does Mongoose return promise?

Does mongoose query returns Promise? Mongoose queries are not promises. They have a . then() function for co and async/await as a convenience.

What does Mongoose exec return?

exec() function returns a promise, that you can use it with then() or async/await to execute a query on a model "asynchronous".


1 Answers

First let's consider your conditions:

user == [] || user == null || user == undefined || user == {} || user == '[]'
  1. The user == [] will always be false. Even [] == [] is always false.
  2. If you're testing user == null then you don't need user == undefined and vice versa because null == undefined is always true (unlike null === undefined which is not).
  3. user == {} will always be false. Even {} == {} is always false.
  4. user == '[]' can be true if user literally contains the string [] but this will never happen in Mongo

Here 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
  }
});
like image 133
rsp Avatar answered Sep 29 '22 01:09

rsp