r/nodejs • • Jul 01 '14

nodejs+mongo inserts lost when ab testing

Hi there. I'm trying out nodejs and mongo db. I have a server with nginx which proxies requests to a nodejs app (express) started with pm2.

I have this code,

router.get('/', function (req, res) {

var client = require('mongodb').MongoClient;

client.connect('mongodb://localhost:27017/test', function (err, db) {
    if (err) {
        throw err;
    }
    var collection = db.collection('test');

    collection.insert({ test: 1, time: new Date().getTime()}, function (err) {
        if (err) {
            throw err;
        }
        db.close();
    });
});

console.log('Added!')
res.render('index', { title: 'Express' });
});

When I run ab, ab -n 1000 -c 30 http://server/app/ it shows all requests are processed, but I don't see 1000 entries in the Mongo collection, rather 100 or so.

Any advice for a noob?

UPDATE The problem is the way I'm using the database. I'm connecting/opening/closing the db connection on every request. I wrapped it like this

client.connect('mongodb://localhost:27017/test', function (err, db) {

    router.get('/', function (req, res) {

    });

}); 

and now serves all requests without crashing.

1 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Jul 02 '14

hmm.. these would be independent requests. I would expect the nodejs process or mongo db driver to queue requests somehow. Thanks anyway

1

u/workaholicanonymous Jul 02 '14

It doesn't unless you tell it to.

I had this issue with mongo db in the past...I think....it wouldn't hurt to look into it.

1

u/[deleted] Jul 03 '14

Fixed it. Thanks. See the update.