0

I have a mongoose schema. I want to count records in a collection that corresponds to the schema. I don't want to count all records, but records that satisfies some criteria. How to execute this count synchronously?

In mongodb console I can do `db.mycollections.find(criteria).count()". How to execute this query from mongoose code?

1
  • You can't do synchronous queries in node.js. Commented Oct 25, 2013 at 16:16

1 Answer 1

1

Mongoose, like most nodejs modules, is not designed to be used for synchronous code execution. This would result in all of the app's execution stalling while the database is performing the query, which could be a long time.

There is an asynchronous count function which you call on your model.

Assuming you made a model from your schema like so:

var MyModel = mongoose.model('mySchemaCollection', mySchema);

You can get the count like so:

MyModel.count(criteria, function (err, count) { 
    /* handle count */ 
});

You can read more about count, as well as other types of querying, from the Mongoose Documentation.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.