使用 mongoose 清除数据

使用 mongoose 封装的方法来删除 mongodb 数据库中的 database、 collections、docs。

  • 删除数据库

1
2
3
4
5
6
7
8
9
10
var mongoose = require('mongoose');

var dbUri = "mongodb://localhost/test";
mongoose.connect(dbUri, function() {
var db = mongoose.connection.db;
db.dropDatabase(function(err) {
if (err) return cb(err);
mongoose.disconnect();
});
});
  • 删除所有collections

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var mongoose = require('mongoose');
var async = require('async');
var _ = require('lodash');

var dbUri = "mongodb://localhost/test";

mongoose.connect(dbUri, function() {

var db = mongoose.connection.db;

db.collections(function (err, collections) {

var collectionsName =
_(collections)
.pluck('collectionName')
.filter(function(collectionName) {
return collectionName.split('.')[0] !== 'system';
})
.value();

async.forEach(
collectionsName,

function(collectionName, done) {

db.dropCollection(collectionName, function(err) {
if (err && err.message != 'ns not found') return done(err);
done(null);
})
},

function(err) {
mongoose.connection.close(function() {});
});
});
});
  • 删除所有 collections 下的 docs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var mongoose = require('mongoose');
var async = require('async');
var _ = require('lodash');

var dbUri = "mongodb://localhost/test";

mongoose.connect(dbUri, function() {

var db = mongoose.connection.db;

db.collections(function(err, collections) {

var collectionsWithoutSystem = _.filter(collections, function(collection) {
return collection.collectionName.split('.')[0] !== 'system';
});
async.forEach(
collectionsWithoutSystem,

function(collection, done) {

collection.remove({}, function(err) {
if (err) return done(err);
done(null);
});
},

function(err) {
mongoose.connection.close(function() {});
});
});
});