MongoError: ns not found when try to drop collection

node.jsMongodbMongoose

node.js Problem Overview


Mongoose throw an error i.e, "MongoError: ns not found" when i try to drop collection.

Here is my mongoose code:

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

Error:

> err { [MongoError: ns not found]
name: 'MongoError',
message: 'ns > not found',
ok: 0,
errmsg: 'ns not found' }

node.js Solutions


Solution 1 - node.js

MongoError: ns not found occurs when performing actions on collections that don't exist.

For example, attempting to drop indexes before an explicit collection creation has occurred or before adding a document to the collection which implicitly creates the collection.

Solution 2 - node.js

Status(ErrorCodes::NamespaceNotFound, "ns not found"); is thrown when you try to drop a collection, a view or an index that doesn't exist.

For example: _dropCollection

Other than that, there is no need to explicitly check if a collection already exists before doing any CRUD operations.

Solution 3 - node.js

This is my mongodb connection interface to avoid drop collection error:

'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]);
            }
        }
    }
};

Solution 4 - node.js

This is how I check the collection exists, before attempting to drop.

if (db.listCollections().toArray().includes(collection)) {
   await db.collection(collection).drop();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvineetView Question on Stackoverflow
Solution 1 - node.jsAndrew HomeyerView Answer on Stackoverflow
Solution 2 - node.jsAdam RosenthalView Answer on Stackoverflow
Solution 3 - node.jsLitoView Answer on Stackoverflow
Solution 4 - node.jsDanView Answer on Stackoverflow