4

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.

Stennie
  • 63,885
  • 14
  • 149
  • 175
The Angry Saxon
  • 792
  • 2
  • 7
  • 24

1 Answers1

7

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);
   });
Ben
  • 5,024
  • 2
  • 18
  • 23
  • @Ben, what if 'searchParams' in properties.find(searchParams) is an Arrary of json objects? I meant i need to search for records matching with multiple values? – ramya Dec 19 '17 at 09:45
  • @yadavr, find() takes an object, so you can't really pass array to it but in searchParams. You can, however, have query property that can search records matching with multiple values. See mongodb document more info: https://docs.mongodb.com/manual/reference/method/db.collection.find/ – Ben Dec 27 '17 at 19:02