Nodejs mongodb本地驱动程序,asynchronous请求的执行顺序

有没有人有一个很好的方式订购mongodb请求,因为Nodejs是asynchronous的。

假设我将data1插入到数据库中,并立即请求读取数据,那么在将数据写入数据库之前,可能会执行读取请求。

有没有一个很好的方法,而不是在请求上强制同步行为?

你可以简单地使用callback,只有在插入完成后才会被调用。

var mongodb = require('mongodb'), client = new mongodb.Db('test', new mongodb.Server('127.0.0.1', 27017, {})), test = function (err, collection) { collection.insert({ hello : 'world' }, {safe:true}, function(err, docs) { collection.count(function(err, count) { console.log(count); }); collection.find({ hello : 'world' }).toArray(function(err, results) { console.log(results); }); }); }; client.open(function(err, client) { client.collection('test_collection', test); }); 

如果您需要更复杂的function,请查看asynchronous模块。 它应该帮助你组织许多callback。