dan_paul
dan_paul

Reputation: 309

In Mongoose, what is passed to the callback as the record by Model.find() if no matching records are found?

In my callback, I am attempting to test whether my call to Model.find() found any results. The record passed to the callback for Model.findOne(), is null but this does not seem to be the case for Model.find() which typically "finds" all matching records. So, what exactly is Model.find() passing?

Below are various tests I made to try to determine what is being passed to the callback as record:

author.model.find({userName: 'nameNotInDB'}, function(err, record)
{
    if(err){console.log(err)
    }else{
        console.log(record); //~> []
        console.log(record == []); //~> false
        console.log(record == null); //~> false
        console.log(record == undefined); //~> false
        console.log(record == ''); //~> true
        console.log(record === ''); //~> false
        console.log(record == false); //~> true
        console.log(record === false); //~> false
    }

});

Upvotes: 0

Views: 43

Answers (1)

Andreas Hultgren
Andreas Hultgren

Reputation: 14953

console.log(typeof record === typeof []) // True

Your test (record == []) fails because comparing complex types (objects and arrays) will only be true if they are referencing the same object.

Update, better test:

console.log(Array.isArray(record)) // True

Upvotes: 2

Related Questions