简体   繁体   English

Mongodb findone方法不起作用

[英]Mongodb findone method does not work

function updateMongo(url, cached) {
    console.log("Update mongo called");
    MongoClient.connect('mongodb://127.0.0.1:27017/dbnerds', function(err, db) {
        if(err) {
            return console.log(err);
        }
        var cache = db.collection('cache');
        cache.insert({url: url, image: null}, {safe: false}, null);
        cache.findOne({ url: url }, function(err, result) {
            console.log(result);
        });
        db.close();
    });
};

As you can see from my code, that I insert url into mongodb, but when I do findOne operation, it seems it does not work. 从我的代码中可以看出,我将url插入到mongodb中,但是当我执行findOne操作时,它似乎无效。 The console did not print out any result. 控制台没有打印出任何结果。 What is wrong with here? 这有什么问题?

The problem is because there is no guarantee that the call to .insert() has finished when the call to .findOne() is executed. 问题是因为无法保证在执行.findOne()调用时对.insert()的调用已完成。

Try using the following approach instead: 请尝试使用以下方法:

function updateMongo(url, cached) {
    console.log("Update mongo called");
    MongoClient.connect('mongodb://127.0.0.1:27017/dbnerds', function(err, db) {
        if(err) {
            return console.log(err);
        }
        var cache = db.collection('cache');
        cache.insert({url: url, image: null}, {safe: false}, function(err, n) {
            // Make the call to findOne until insert has finished
            cache.findOne({ url: url }, function(err, result) {
                console.log(result);
                // close the DB after you are done
                db.close();
            });
        });
    });
};

Notice how I moved the call to findOne() to be the callback function executed after the insert has finished. 注意我是如何将对findOne()的调用移动到插入完成后执行的回调函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM