NodeJS Mongoose collection.remove不工作

时间:2015-04-29 14:00:18

标签: node.js mongodb mongoose

尝试在单元测试运行之前删除所有集合中的所有文档...

var collections = mongoose.connection.collections;
async.eachSeries(_.keys(collections), function(key, cb){

  collections[key].remove(function(){
    //Never gets here, doesn't drop the collection and doesn't error.
    cb();
  });
}

但是remove()中的回调永远不会被触发。 我已经注销了collections[key],它确实解析了一个集合。

没有错误,但是因为它从不运行回调而超时。

我也试过循环模型并调用remove,但它的问题相同。

我在这做错了什么?我能看到的任何日志?

3 个答案:

答案 0 :(得分:0)

您可以尝试使用drop方法:

var async = require("async"),
    _ = require("underscore"),
    collections = _.keys(mongoose.connection.collections);

async.forEach(collections, function(key, done) {
    var collection = mongoose.connection.collections[key]
    collection.drop(function(err) {
        if (err && err.message != "ns not found") {
            done(err);
        } else {
            done(null);
        }
    })
}, callback);

答案 1 :(得分:0)

编辑:尝试以下方法:

var collections = mongoose.connection.collections;
async.eachSeries(_.keys(collections), function(key, cb){
  mongoose.connection.db.collection(key, function(err, col) {
    col.remove({}, function(){
      cb();
    });
  })
}

答案 2 :(得分:0)

无关的问题,它没有连接到测试环境中的数据库。但是没有报告错误,并且由于猫鼬模型,它有一个有效的集合列表。

我在测试设置中添加了以下内容以注销错误和其他信息,以帮助在将来找到这些问题...

mongoose.connection.on('connected', function () {
    console.log('Mongoose default connection open to ' + config.db.url);
});


mongoose.connection.on('error',function (err) {
    console.log('Mongoose default connection error: ' + err);
});

mongoose.connection.on('disconnected', function () {
    console.log('Mongoose default connection disconnected');
});
相关问题