Michele Prandina
Michele Prandina

Reputation: 23

node.js + mongoose connection and creation issue

I just want to know if when I set a mongoose connection and I define some models, (previously adding their appropriate requires on app.js, or wathever), the model, if not exist, will be created automatically the first time when I run node app.js?

Is this kind of logic correct?

If not, do I have to create before my mongoDB collections, models and so on?

I was thinking to an automatic creation of the mongo db collection when I first run the app.js

Thanks! Michele Prandina

Upvotes: 0

Views: 85

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59763

Schemas (and models) are a client-side (node.js) manifestation of your data model. A few things, like the indexes you've defined, are created upon first use (like saving a document for example). Nearly everything else is delay created, including collections.

If you want consistent behavior regarding your models (and their associated schemas), you'll need to make sure they're loaded prior to any access of the associated database. It doesn't really matter where you put them, as long as they are created/executed prior to usage. You might for example:

app.js

models\Cheese.js
      \Cracker.js

Then, in app.js:

var Cheese = require('Cheese.js');
var Cracker = require('Cracker.js');

Assuming, of course, you've exported the models:

model.exports = mongoose.model('Cheese', 
                       new mongoose.Schema({
                           name: String,
                           color: String 
                       })
                );

Upvotes: 1

Related Questions