我通过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
有什么问题?
答案 0 :(得分:2)
您正在使用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) {
mongoose.connection.db.dropCollection(e.name);
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);
}
});
});