mongodb nodejs each vs toArray

妖精的绣舞 提交于 2019-12-05 01:47:52

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/24724552/mongodb-nodejs-each-vs-toarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!