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.

2
  • 1
    Why don't use just use result.length instead of count? Commented Jul 13, 2014 at 17:29
  • Ahhh thank you I didn't know about this thanks that's exactly the sort of thing I was hoping to hear Commented Jul 13, 2014 at 17:34

1 Answer 1

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);
   });
Sign up to request clarification or add additional context in comments.

2 Comments

@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?
@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: docs.mongodb.com/manual/reference/method/db.collection.find

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.