简体   繁体   中英

Mongo/Monk count of objects in collection

I'm 2 hours into Mongo/Monk with node.js and I want to count how many objects I have inserted into a collection but I can't see any docs on how to do this with Monk.

Using the below doesn't seem to return what I expect

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/mydb');
var collection = db.get('tweets');
collection.count() 

Any ideas?

You need to pass a query and a callback. .count() is asynchronous and will just return a promise, not the actual document count value.

collection.count({}, function (error, count) {
  console.log(error, count);
});

Or you can use co-monk and take the rest of the morning off:

var monk = require('monk');
var wrap = require('co-monk');
var db = monk('localhost/test');
var users = wrap(db.get('users'));
var numberOfUsers = yield users.count({});

Of course that requires that you stop doing callbacks... :)

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