node.js mongojs findOne callback returning error as null
Asked Answered
H

1

5

Presently being driven up the wall by this error.

I am running a node.js app with the mongojs wrapper for mongodb. I Started mongod on the default port, then ran

var db = require('mongojs').connect('localhost:27017/my_db');
var users = db.collection('users');    
users.findOne({'fb_id' : fbUserMetadata.id}, function(err, user) {
                console.log(err);
                console.log(user);
                debugger;

    });

however err and user are both 'null'. To my knowledge, err should be populated with some kind of data even if it doesn't find anything.

How do I get the callback function to work properly? Pardon the newbie question.

Hypergolic answered 20/8, 2012 at 0:23 Comment(0)
R
10

When the findOne query doesn't find at least one matching document, the second parameter of the callback (in this case user) is set to null. It's not an error, so err is also null. So what you're seeing is the expected no-match-found response.

Update

Note that findOne has been deprecated in the 2.0 driver, but its replacement also exhibits this same behavior:

users.find({'fb_id' : fbUserMetadata.id}).limit(1).next(err, doc) {
    // doc is null if a matching document wasn't found
});
Rasberry answered 20/8, 2012 at 0:33 Comment(1)
So simple, yet couldn't find this on the API documentation.Dogger

© 2022 - 2024 — McMap. All rights reserved.