Reputation: 11
I'm new in Node.js, and I've created a module based on mongoose but i have a problem with the configuration function.
Actually my module uses the mongoose.connect connection, but i want to change it in order to use mongoose.createConnection. To do this I've created an init function that accept the connection string as an argument.
My problem is "How can I module.exports the connection into my module?"
For example:
// server.js
var mymodule = require('mymodule');
mymodule.init('http://localhost:27017/test');
// mymodule/index.js
var mongoose = require('mongoose');
module.exports = {
init: function(connString){
module.exports = connection = mongoose.createConnection(connString); // this is wrong
}
}
// mymodule/user.js
// I want to use the connection to create the mongoose 'User' model
var mongoose = require('mongoose');
var connection = require // I don't know
var UserSchema = new mongoose.Schema({
name: String
});
module.exports = connection.model('User', UserSchema);
Thanks for any advice.
Upvotes: 1
Views: 427
Reputation: 32127
mongoose.createConnection()
is synchronous, so you should be able to just return the connection from your method.
var mongoose = require('mongoose');
module.exports = {
init: function(connString){
return mongoose.createConnection(connString);
}
}
Then you can do:
var module = require('myModule');
var db = module.init('mongodb://etc/db');
Upvotes: 1