Attaching a database to a model?

43 views
Skip to first unread message

Rob Polak

unread,
Mar 26, 2015, 11:53:03 AM3/26/15
to mongoo...@googlegroups.com
I am running into a dillemia.. I would like the ability to create a mongoose model without having a hard connection to the database at the time of creation.. i.e.

UserModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var mongoCore = require('../../src/core/mongoCore');
var SALT_WORK_FACTOR = 10;


module.exports = function() {

  var UserSchema = new Schema({
    username: { type: String, required: true, index: { unique: true }, min: 4 },
    password: { type: String, required: true, min: 5 },
    first_name: { type: String, required: true, min: 2 },
    last_name: { type: String, required: true, min: 2 }
  });

  return mongoose.model('inventory_users', UserSchema);

}();

However, this fails because I did not attach my database instance to the model

i.e.:

UserModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var mongoCore = require('../../src/core/mongoCore');
var SALT_WORK_FACTOR = 10;


module.exports = function() {

  var UserSchema = new Schema({
    username: { type: String, required: true, index: { unique: true }, min: 4 },
    password: { type: String, required: true, min: 5 },
    first_name: { type: String, required: true, min: 2 },
    last_name: { type: String, required: true, min: 2 }
  });
  var db = mongoose.createConnection(dbConfig.url, dbConfig.options);
  return db.model('inventory_users', UserSchema);

}();


My question is.. how can I attach the database after the fact (i.e. only attach the database if I need to do a database operation).. or am I missing something?

Thanks!!

Rob

Valeri Karpov

unread,
Mar 27, 2015, 10:48:17 AM3/27/15
to mongoo...@googlegroups.com
Create a new connection using

```
var db = mongoose.createConnection(); // Don't pass any arguments!
```

Then create your models normally. When you want to explicitly open a connection, use `db.open(dbConfig.url, dbConfig.options)`, or `db.openSet(dbConfig.url, dbConfig.options)` if you're connecting to multiple hosts (e.g. replica set, multi-mongos). Mongoose will buffer queries for you until the connection is successfully made. Keep in mind, you need to explicitly use open() vs openSet(), you don't get createConnection()'s syntactic sugar on top of that.

However, I wouldn't recommend this pattern in most cases. If you're writing a web server, it should almost certainly connect to mongod on server start as opposed to in a transaction. Easier to make sure you're not opening unnecessary connections and easier to test.
Reply all
Reply to author
Forward
0 new messages