beNerd
beNerd

Reputation: 3374

unable to get count in mongodb collection.find

I am using mongoose ODM for a application. I am trying to count the number of items returned by a model like this:

 app.post("/verifyLogin",function(request,response){
var usr=request.body.username;
var pass=request.body.password;

response.send(userModel.find({$and:[{username:"admin"},{password:"admin"}]}).count());

});

But i get in return:

   {
  "options": {
    "populate": {}
  },
  "_conditions": {
    "$and": [
      {
        "username": "admin"
      },
      {
        "password": "admin"
      }
    ]
  },
  "_updateArg": {},
  "op": "count"
}

I expected a number :(

Upvotes: 0

Views: 787

Answers (1)

soulcheck
soulcheck

Reputation: 36767

One way of doing this is to use Model.count method, in your case:

userModel.count({$and:[{username:"admin"},{password:"admin"}]}, function(err, result) {
    if (err) {
       //handle errors
    } else {
       response.send({count :result});
    }
});

Also: you're in node.js world - use callbacks.

The result you're getting now is the result of the count call on the Model.find() result (which, i think, is a query object), not the count of the query results.

Upvotes: 1

Related Questions