简体   繁体   中英

async.parallel on mongodb and Node.js

In the following code:

var collection = db.collection('colname');
    async.parallel([
        function(callback(){collection.find({category:'a'}).sort({rank:1}).toArray(callback)},
        function(callback(){collection.find({category:'b'}).sort({rank:1}).toArray(callback)}
    ], function(err, result){
        if (err) throw err;
        console.log('a');
        concole.log(result);
        console.log('b');
    });

If I run the above code, which is inside MongoClient.connect function by the way, I got a on the screen but didn't get b . So it looks like console.log(result) stops running the code. How can I fix it and run the query in parallel?

Thanks.

There are many obvious syntactical errors but apart from that, code seems fine to me. I haven't used used mongo driver directly, so I can't be completely sure.

I use mongoose, so I translated your code to work with mongoose, and I could get it to work. Also category model that I have used is from one of my projects, so its a bit different than what you have posted. Here is my code:

( function() {
var mongoose = require('mongoose'), db, async = require('async');
mongoose.connect('mongodb://127.0.0.1/test');
db = mongoose.connection;   
db.once('open', function callback() {
    var collection = require('../src/db').Category;
    async.parallel([
    function(callback) {
        collection.find({
            categoryType : 1
        }).sort({
            categoryName : 1
        }).exec(callback);
    },
    function(callback) {
        collection.find({
            category : 2
        }).sort({
            categoryName : 1
        }).exec(callback);
    }], function(err, result) {
        if (err)
            throw err;
        console.log('a');
        console.log(result);
        console.log('b');
    });
});
}());

Hope this is useful to you.

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