2012-07-12 76 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