Mongoose/MongoDB Create Collection if not exists based on Schema

4.8k views Asked by At

I want to create a collection if it doesnt exists and fill it with the preset defaults from a Mongoose Schema.

The idea is to create AND populate a Database on first run or do nothing if it already exists.

I have a working solutions but I was wondering if there is a better way to do it, here's my solution:

settings.js (Schema)

var mongoose = require('mongoose');

// define the schema for our account data
var settingsSchema = mongoose.Schema({
  cmdPrefix : {type:String, default: '!'},
  fontColor: {type: String, default:'<font color=\'#89D2E8\'>'},
  loggedOn: {type:Date, default:Date.now}


},{timestamps : true});

// methods ======================


// create the model and expose it to our app
module.exports = mongoose.model('Settings', settingsSchema);



start.js(Start File)

const Settings = require('./config/models/settings.js');

...

mongoose.connect('mongodb://localhost/testdb'); // connect to our database

settingsExists();

...

function settingsExists() {
  Settings.find({},function(err, result) {
    if (result.length > 0) {
      console.log('found ' + result);
    } else {
      console.log('not found, creating');
      let newSettings = new Settings({});
      newSettings.save();
    }
  });
}
1

There are 1 answers

0
Satyam Singh On

Buddy Do Like This

if (!mongoose.models.Settings) {
           mongoose.model('Settings', settingsSchema);
    }

module.exports = moongose;