简体   繁体   中英

syncronous query in mongodb (+mongoose) + node.js

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM