Mongoose - 在find方法中使用变量返回null

时间:2014-06-10 02:35:04

标签: node.js mongodb express mongoose

在搜索对象时尝试在mongoose中使用find方法时遇到问题。

当我这样做时:

var newObj = MyObject();

newObj.save(function(err) {
    if(err) throw err;       
});

MyObject.findOne({ _id: newObj._id }, function(err, obj) {
    console.log(obj);
});
返回

null。但是,如果说" _id"像这样使用一个值:

....({ _id: 'abc1233dff4f24f' }....

然后返回对象。任何想法为什么会这样?似乎任何时候使用任何变量,返回的值都是null。

1 个答案:

答案 0 :(得分:2)

在您尝试查找对象之前,没有理由相信save已完成。您应该在回调中进行查找:

newObj.save(function(err) {
    if(err) throw err;  
    MyObject.findOne({ _id: newObj._id }, function(err, obj) {
        console.log(obj);
    });     
});