2012-07-12 51 views

回答

51

是的,虽然你通过本地MongoDB驱动程序,而不是Mongoose本身。假设需要连接的mongoose变量,则可以通过mongoose.connection.db访问本机Db对象,该对象提供了dropCollectiondropDatabase方法。

// Drop the 'foo' collection from the current database 
mongoose.connection.db.dropCollection('foo', function(err, result) {...}); 

// Drop the current database 
mongoose.connection.db.dropDatabase(function(err, result) {...}); 
+0

非常感谢! – WHITECOLOR 2012-07-15 17:59:47

+0

请注意,这些方法也会返回promise,所以您可以执行诸如await mongoose.connection.db.dropCollection('foo');'而不是用回调挣扎 – 2017-11-11 20:04:40

1

Mongoose引用每个模型的连接。因此,您可能会发现从单个模型中删除数据库或集合也很有用。

例如:

// Drop the 'foo' collection from the current database 
User.db.db.dropCollection('foo', function(err, result) {...}); 

// Drop the current database 
User.db.db.dropDatabase(function(err, result) {...}); 
1

在猫鼬4.9.8,您可以使用下面的删除与模型相关联的集合。

ModelName.remove({}, function(err, row) { 
    if (err) { 
     console.log("Collection couldn't be removed" + err); 
     return; 
    } 

    console.log("collection removed"); 
}) 
+0

这不会删除集合。它删除集合中的所有记录。对于大量记录,它可能需要很长时间,导致超时... – user3616725 2017-10-19 14:24:59