Saani
Saani

Reputation: 782

Mongo with Express: what does find return

I am developing an application in Express with Mongo, in which i have to query, whether a document exits in the collection or not. I am doing this:

var dept= req.body.dept;
var name= req.body.name;
mongoose.model('User').find({'dept': dept, 'name': name}, function(err, user){
        if(err){
            res.render('user/test1');
        }else{
            res.redirect('/');
        }
    });

What I want to do is to check if that document exits in the collection and upon true condition, i want to redirect to another page otherwise render the current page. But when I pass the wrong input, even then it goes to the else part and redirects it.

Upvotes: 0

Views: 2110

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50426

Well you are actually using mongoose, so there is in fact a distinction between what is returned by this specific version ( abtraction ) to what the base driver itself returns.

In the case of mongoose, what is returned is either an array of results or a null value if nothing is found. If you are looking for a singular match then you probably really want findOne() instead of a result array.

But of course the case would be a null result with either function if not returned as opposed to an err result that is not null, which is of course about specific database connection errors rather than simply that nothing was found.

The base driver on the other hand would return a "Cursor" ( or optionally considered a promise ) instead, which can either be iterated or converted to an array like mongoose does via the .toArray() method. The .findOne() method of the base driver similarly returns either a result or a null document where the conditions do not match.

mongoose.model('User').findOne({'dept': dept, 'name': name}, function(err, user){
    if(err){
        // if an error was actually returned
    } else if ( !user ) {
        // Nothing matched, in REST you would 404
    } else {
        // this is okay
    }
});

In short, if you want to test that you actually found something, then look at the user value for a value that is not null in order to determine it matched. If it is null then nothing was matched.

So no match is not an "error", and an "error" is in fact a different thing.

Upvotes: 2

Related Questions