Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

javascript - node.js mongojs findOne callback returning error as null

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...