Home > Software design >  Is there a way in mongoose to not create a collection if not found?
Is there a way in mongoose to not create a collection if not found?

Time:02-03

We are creating a discord bot for task management based on teams. We're using a collection as a team. In code to find a team and add tasks to it we use: const Team = await mongoose.connection.collection(teamName, {strict: true}); and strict is supposed to make it so that the collection isn't created when it's not found but instead this happens:

creating task even though team doesn't exist

I've tried with no luck as the mongoose has no documentation on the options and everything I've tried doesn't work.

How do I make mongoose.connection.collection(teamName) return an error if teamName isn't a collection name/isn't found?

CodePudding user response:

You are right, strict: true should do it, but doesn't. Mongoose doesn't mention the options it accepts, though usually it takes the ones used by the underlying mongo client. But it does mention in the documentation that it makes missing collections:

Retrieves a collection, creating it if not cached.

I looked into the repo, and the collection method always makes a missing collection

Connection.prototype.collection = function(name, options) {
 const defaultOptions = {
   autoIndex: this.config.autoIndex != null ? this.config.autoIndex : >this.base.options.autoIndex,
   autoCreate: this.config.autoCreate != null ? this.config.autoCreate : >this.base.options.autoCreate
 };
 options = Object.assign({}, defaultOptions, options ? utils.clone(options) : {});
 options.$wasForceClosed = this.$wasForceClosed;
 if (!(name in this.collections)) {
   this.collections[name] = new Collection(name, this, options);
 }
 return this.collections[name];
};

The mongo-client collection does take a strict parameter. You can access it via mongoose.connection.client

Update

Here is how you can call it:

mongoose.connection.client.db().collection(teamName, {strict: true}, function (error, collection) {
  console.log('error', error);
  console.log('collection', collection);
})

CodePudding user response:

You can use this code to check if a collection exists or not in a specific database - and then perform actions as needed.

const mongoose = require('mongoose');
const uri = 'mongodb://127.0.0.1:27017/';
const opts = { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
    dbName: 'test' 
};

(async () => {
    const conn = await mongoose.createConnection(uri, opts);
    let collNames = await conn.db.listCollections().toArray();
    collNames = collNames.map(e => e.name);
    console.log(collNames);
    console.log(collNames.includes('existing_coll'));       // true
    console.log(collNames.includes('non_existing_coll'));   // false
    await conn.close();
})(uri, opts);
  •  Tags:  
  • Related