2012-07-12 2 views

答えて

51

はい、ネイティブのMongoDBドライバを使用しますが、Mongoose自体は使用しません。必要な接続されたmongoose変数を仮定すると、ネイティブのDbオブジェクトはmongoose.connection.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

+0

これらのメソッドも約束を返してくれるので、コールバックで苦労するのではなく、 'await mongoose.connection.db.dropCollection( 'foo');のようにすることができます。 –

1

マングースはすべてのモデルで接続を参照します。したがって、データベースやコレクションを個々のモデルから削除すると便利です。例えば

// 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

、あなたは、モデルに関連付けられているコレクションを削除するには、以下を使用することができます。

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

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

これでコレクションは削除されません。コレクション内のすべてのレコードが削除されます。多数のレコードの場合、タイムアウトの原因となるかなりの時間がかかります... – user3616725

関連する問題