我对NodeJS
和MongoDB
我正在尝试做一个非常基本的东西,但它似乎不起作用。
我确定我在某处遗漏了一些东西。
基本上,我试图根据 id 从数据库中查找用户。
这是我的代码:
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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
我假设你id
的类型string
如果是这种情况,您需要将其转换为适当的 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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3115 次 |
最近记录: |