Answer a question

I have a directory structure

./lib
./lib/model1.js
./lib/model2.js

Both models connect to the same MongoDB instance using mongoose, but define different models:

// model1.js
var mongoose = require ('mongoose');
mongoose.connect ('bla')
var db = mongoose.connection;

var schema1, model1;

db.on('error', console.error.bind(console, 'database, why you no connect?'));

db.once('open', function callback () {

  schema1 = mongoose.Schema({
    // some properties
  });

  model1 = mongoose.model1 ('model1', schema1);

});

What is the best way to create the database connection once and reuse it for each of the models? What is the best directory structure? Maybe ./lib/middleware/db.js?

This question seems relevant but it's using the mongodb npm module instead of mongoose, the question is unclear, and all of the author's comments have been deleted.

Answers

You should only be calling mongoose.connect once, in your application's startup code. That will create the default connection pool for your application.

Your model1.js and model2.js files create their models via calls to mongoose.model which binds them to the default connection.

So it's actually handled for you by Mongoose.

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐