mongoose删除mongodb某个库的所有collection

上次实现过获取某个库下的所有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);
    })
});
posted @ 2020-01-16 16:01  慕尘  阅读(876)  评论(0编辑  收藏  举报