1

Does anyone have a nice way of ordering mongodb requests since Nodejs is async.

Say that I insert data1 into the database, and I immediately request to read that data, my read request might get executed before the data is written to the database.

Is there a nice way around this instead of forcing synchronous behavior on the requests?

1 Answer 1

2

You can simple use callback that will be called only after insert will be completed.

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

If you need more complex functionality look at async module. It should help you to organize many callbacks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.