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();
});
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
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
If you want to use the default connection and use the
mongoose.model(...)syntax instead, then do not usemongoose.createConnection(...). Instead, use--Brian