0

我有这个函数可以从 mongo db 中检索特定用户:

exports.findById = function(req, res){
    var id = req.params.id;
    db.collection('Users', function(err, collection){
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item){
        findPhotoByUserId(item._id, function(photo){
            console.log('photo: ' + photo);
         });            
    });
});
};

而另一个获取用户的照片,将用户的 ID 传递给它:

var findPhotoByUserId= function(userId, cb){
    db.collection('Photos', function(err, collection){
        collection.findOne({'userId': userId}, function(err, item){
            if(!err)
                cb(item);
        });
    });
};

问题:当我调用函数“findById”时,照片项为空。但是,如果我将显式用户 ID 放在这里“collection.findOne({'userId': '522bae4a3ee1be8005000001'}....”,该函数将返回预期的照片项。

有人可以帮我解决这个问题吗?

谢谢!

4

2 回答 2

0

好吧,我解决了我的问题!

在这个函数中:

var findPhotoByUserId= function(userId, cb){
    db.collection('Photos', function(err, collection){
        collection.findOne({'userId': userId.toString()}, function(err, item){
            if(!err)
                cb(item);
        });
    });
};

'userId' 必须转换为字符串。

谢谢!

于 2013-09-11T01:55:11.273 回答
0

我有同样的问题。我通过在“mongodb”库中使用 ObjectID 使我的代码工作:

var ObjectID = require("mongodb").ObjectID;
//more code here
query._id = { $gt: ObjectID(myId) }
于 2013-09-10T05:54:17.147 回答