mongodb nodejs each vs toArray

The Angry Saxon picture The Angry Saxon · Jul 13, 2014 · Viewed 16.6k times · Source

I've had a quick look around and not found anything that's satisfied me with an answer but basically I've started to use node.js with express and mongodb to create a webapi rather than the usual .Net MVC Web API route.

One thing I've noted though is in order to return a collection of results I'm doing it in a rather bulky way, or that's how it feels at least.

app.get('/property', function (req, res) {
    var propArray = [];
    MongoClient.connect(settings.connection,
        function (err, db) {
            if (err) throw err;

            var properties = db.collection("PROPERTIES");

            var searchParams = {
                Active: true,
                Deleted: false
            }

            properties.count(searchParams, function (err, count) {
                properties.find(searchParams).toArray(function (err, result) {
                    for (i = 0; i < count; i++)
                        propArray.push(new models.propertyModel(result[i]));

                    db.close();

                    return res.json(propArray);
                });
            });
        }
    );
});

Now I've noted that there's a .each function rather than .toArray which I would prefer to use as I could cut out the .count function but obviously you can only return a response once. I wondered if you guys could enlighten me with some of your mongo knowledge.

properties.find(searchParams).each(function (err, result) {
    return res.json(result);
});

Something like that, cutting out 6 lines of code and an extra call to the database.

Answer

Ben picture Ben · Jul 13, 2014

The count() can still be cut out with toArray():

   properties.find(searchParams).toArray(function (err, result) {
     var i, count;
     for (i = 0, count = result.length; i < count; i++) {
       propArray.push(new models.propertyModel(result[i]));
     }
     db.close();
     return res.json(propArray);
   });