在MongoDB中按ID查找返回null [英] Finding by id in MongoDB returns null

查看:150
本文介绍了在MongoDB中按ID查找返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对NodeJSMongoDB

我正在尝试做一个非常基本的东西,但是它似乎没有用.
我确定我在某处缺少东西.

I am trying to do a very basic stuff but it does not seem to be working.
I am sure that I am missing something somewhere.

基本上,我正在尝试根据ID从数据库中查找用户.
这是我的代码:

Basically, I am trying to find a user from the DB based on the id.
Here is my code:

function findUser(id, cb) {
    MongoClient.connect(cs, function(err, db) {
        var col = db.collection('users');
        col.findOne({ _id: id }, function(err, user) {
            // Value of user here is always null
            // However, if I manually check the database, 
            // I can clearly see that the user with the 
            // same id does exists.
            return cb(err, user);
        });
    });
}

推荐答案

我假设您的id类型为string

在这种情况下,您需要将其转换为适当的Mongo ObjectID

If this is the case, you need to convert it to a proper Mongo ObjectID

尝试此代码:

var ObjectID = require('mongodb').ObjectID;

function findUser(id, cb) {
    MongoClient.connect(cs, function(err, db) {
        var col = db.collection('users');
        col.findOne({ _id: new ObjectID(id) }, function(err, user) {
            return cb(err, user);
        });
    });
}

这篇关于在MongoDB中按ID查找返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆