简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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