上次实现过获取某个库下的所有collection,但是时间久了又忘记了,因此记录下来
获取所有collection名字
var mongoose = require('mongoose'); var link = 'mongodb://username:password@XXXX:27017/test'; mongoose.connect(link, {useNewUrlParser: true},function(err,connection){ connect.db.collections().then(res => { var collections = res.map(function (collection) { return collection.collectionName; }) console.log(collections ); }).catch(err=>{ console.log(err); }) });
删除test库下的全部collection
var mongoose = require('mongoose'); var link = 'mongodb://username:password@XXXX:27017/test'; mongoose.connect(link, {useNewUrlParser: true},function(err,connection){ connect.db.collections().then(res => { var collections = res.map(function (collection) { return collection.collectionName; }) for (var item in collections) { db.dropCollection(collections[item]); } }).catch(err=>{ console.log(err); }) });