Mongoose: "mongoose.createConnection" not work

Created on 25 Apr 2011  路  1Comment  路  Source: Automattic/mongoose

This is the test case, i check the collection "taobao", but can't find the record:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema

var conn = mongoose.createConnection('mongodb://localhost/test');

var TestSchema = new Schema({
    user_id        : {type : Number, index : true}
  , username       : {type : String}
});

var model_name = coll_name = 'taobao';
mongoose.model(model_name, TestSchema, coll_name);

var TAOBAO  = mongoose.model(model_name, coll_name);
var taobao  = new TAOBAO();
taobao.user_id  = 1;
taobao.username = 'shawny';
taobao.save(function(err) {
  if (err) {
     console.log('save failed');
  }
  conn.close();
});

Most helpful comment

require('mongoose') already instantiates a (unopened) connection object, so when you do mongoose.model(...), you are acting on that unopened first connection. To use the new connection at "mongodb://localhost/test" explicitly, do

conn.model(model_name, coll_name); // instead of mongoose.model(...), which uses the default unopened connection

If you want to use the default connection and use the mongoose.model(...) syntax instead, then do not use mongoose.createConnection(...). Instead, use

mongoose.connect('mongodb://localhost/test');

--Brian

>All comments

require('mongoose') already instantiates a (unopened) connection object, so when you do mongoose.model(...), you are acting on that unopened first connection. To use the new connection at "mongodb://localhost/test" explicitly, do

conn.model(model_name, coll_name); // instead of mongoose.model(...), which uses the default unopened connection

If you want to use the default connection and use the mongoose.model(...) syntax instead, then do not use mongoose.createConnection(...). Instead, use

mongoose.connect('mongodb://localhost/test');

--Brian

Was this page helpful?
0 / 5 - 0 ratings