Reputation: 14236
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' }
Upvotes: 96
Views: 76279
Reputation: 19912
Get the list of collections in an async function:
(await db.listCollections().toArray()).find(c => c.name === 'myCollection');
If not exists, it returns undefined
, otherwise a CollectionInfo
object as for example:
{
name: 'myCollection',
type: 'view',
options: { viewOn: '...', pipeline: [ [Object] ] },
info: { readOnly: true }
}
Upvotes: 0
Reputation: 114
This is how I check the collection exists, before attempting to drop.
if (db.listCollections().toArray().includes(collection)) {
await db.collection(collection).drop();
}
Upvotes: 0
Reputation: 488
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.
Upvotes: 12
Reputation: 1332
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]);
}
}
}
};
Upvotes: 5
Reputation: 8098
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.
Upvotes: 132