【问题标题】:MongoError: ns not found when try to drop collectionMongoError:尝试删除集合时未找到 ns
【发布时间】:2016-09-05 07:04:08
【问题描述】:

当我尝试删除集合时,Mongoose 会抛出错误,即“MongoError: ns not found”。

这是我的猫鼬代码:

var mongoose = require('bluebird').promisifyAll(require('mongoose'));
......
......
......   
mongoose.connection.db.dropCollection("myCollection",function(err,affect){
   console.log('err',err);

})

错误:

err { [MongoError: ns not found]
名称:'MongoError',
消息:'ns 没找到',
好的:0,
errmsg: 'ns 未找到' }

【问题讨论】:

  • 你没有连接到数据库(使用mongoose.connect())。
  • mongoose 没有 drop 收集方法。 chekout this 回答以获取更多信息。
  • 是的,我用过 mongoose.connect()。 @robertklep
  • @RajeshDhiman,mongoose.connection.db.dropCollection 方法已经使用,stackoverflow.com/questions/11453617/…

标签: node.js mongodb mongoose


【解决方案1】:

MongoError: ns not found 在对不存在的集合执行操作时发生。

例如,尝试在显式创建集合之前或在将文档添加到隐式创建集合的集合之前删除索引。

【讨论】:

【解决方案2】:

Status(ErrorCodes::NamespaceNotFound, "ns not found"); 在您尝试删除不存在的集合、视图或索引时抛出。

例如:_dropCollection

除此之外,在执行任何 CRUD 操作之前无需显式检查集合是否已经存在。

【讨论】:

    【解决方案3】:

    这是我的mongodb连接接口,避免drop collection错误:

    'use strict';
    
    module.exports = class {
        static async connect() {
            this.mongoose = require('mongoose');
    
            await this.mongoose.connect(process.env.MONGODB_DSN, {
                useNewUrlParser: true,
                reconnectTries: Number.MAX_VALUE,
                reconnectInterval: 5000,
                useFindAndModify: false
            }).catch(err => {
                console.error('Database connection error: ' + err.message);
            });
    
            this.db = this.mongoose.connection.db;
    
            return this.db;
        }
    
        static async dropCollection(list) {
            if (list.constructor.name !== 'Array') {
                list = [list];
            }
    
            const collections = (await this.db.listCollections().toArray()).map(collection => collection.name);
    
            for (let i = 0; i < list.length; i++) {
                if (collections.indexOf(list[i]) !== -1) {
                    await this.db.dropCollection(list[i]);
                }
            }
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 2016-06-15
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 2018-11-30
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多