node.js - Nodejs mongodb原生驱动,异步请求的执行顺序

标签 node.js mongodb

由于 Nodejs 是异步的,有没有人有一个好的方法来排序 mongodb 请求。

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

有没有一个好的方法可以解决这个问题,而不是在请求上强制同步行为?

最佳答案

您可以简单地使用回调,该回调仅在插入完成后调用。

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);
});

如果您需要更复杂的功能,请查看 async模块。它应该可以帮助您组织许多回调。

关于node.js - Nodejs mongodb原生驱动,异步请求的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12251680/

相关文章:

node.js - 通过 NGINX 上传二进制流会阻止对 Node.js 应用程序的所有其他 POST 请求

javascript - 关联数组中的双索引

mongodb - 如何减少 docker-compose 图像中的 mongo 日志详细程度?

node.js - Mongoose 或查询

node.js - 在IIS中发布express js应用程序的步骤

node.js - 如何禁用步骤 CREATE SCHEMA 以续写迁移?

mongodb - 如何使用 MongoDB 聚合框架对嵌套帖子进行分组?

arrays - 使用 mongoose 在对象数组中插入唯一的对象

java - MongoDB:注册编解码器 (Java)

mongodb - mgo/mongodb : aggregate - find all and order by membercount however membercount is an array of member userids