![](/img/trans.png)
[英]Return counter in db.collection.count()'s callback doesn't work, why?
[英]Check if MongoDb database is empty via db.collection.count() - doesn't work
我通过 Mongoose 连接到 MongoDb。 然后,当连接成功时,我想检查数据库是否为空(意味着没有集合) 。 如果为空,我将为数据库提供数据。
我正在使用db.collection.count()
来计算集合,但此代码不起作用。
var dbURI = 'mongodb://localhost/voddb';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + dbURI);
if(mongoose.connection.db.collection.count() == 0) {
//seed database
}
});
它在collection.count()
处引发了我的错误:
TypeError: Cannot read property 'collection' of undefined
怎么了?
您正在使用mongoose.connection.db.collection
这是一个函数,您可以使用mongoose.connection.db.collection('your_collection_name').count()
示例:
var dbURI = 'mongodb://localhost/my_db_name'; mongoose.connect(dbURI); mongoose.connection.on('connected', function () { console.log('Mongoose default connection open to ' + dbURI); // To List all Collections of a Database mongoose.connection.db.listCollections().toArray(function(err, names) { if (err) { console.log(err); } else { names.forEach(function(e,i,a) { console.log("----->", e.name); }); } }); // To Count Documents of a particular collection mongoose.connection.db.collection('users').count(function(err, count) { console.dir(err); console.dir(count); if( count == 0) { console.log("No Found Records."); } else { console.log("Found Records : " + count); } }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.