Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass mongoose connection to module

I'm writing a Node module which whould perform queries to MongoDB.

My module should take as parameter (when I init it with new MyModule(db)) the MongoDB connection and use it inside it.

I was using standard MongoDB without any NPM module and I was passing in my db variable the connection to MongoDB. Now I'm switching to Mongoose and I can't find a way to pass the Mongoose connection to my module.

I don't want to initialize the Mongoose connection inside my module because I want to share it with my tests and with other modules.

How can I do? I've tried passing mongoose to my module but it doesn't work "is not a function".

Edit:

After reading the reply of @Neil Lunn I'm posting this sample of my module:

(function () {
    "use strict";

    /**
     *  various requires
     */

    function TopicManager(dbURI) {
        if (!(this instanceof TopicManager)) { return new TopicManager(dbURI); }
        mongoose.connect(dbURI);
    }

    TopicManager.prototype.save = function (topics, done) {

        var Topic = new mongoose.schema(
            {
                title: { type: String },
                slug: { type: String, index: { unique: true } }
            },
            {collection : "topics"}
        );

        /**
         * Use monguurl on "slug"
         */

        mongoose.update(
            {title: topic.title},
            {upsert: true},
            function (err, numberAffected, raw) {
                if (err) { return done(err); }
                return done(null, raw);
            }
        );    
    };

    module.exports = TopicManager;
})();

It doesn't work because when I use it I get undefined is not a function when it runs new mongoose.

like image 211
Fez Vrasta Avatar asked Jun 29 '14 08:06

Fez Vrasta


People also ask

What is Mongoose connect ()?

mongoose. connect('mongodb://localhost/myapp'); This is the minimum needed to connect the myapp database running locally on the default port (27017). If the local connection fails then try using 127.0. 0.1 instead of localhost.

What is the difference between Mongoose connect and Mongoose createConnection?

My understanding on the official documentation is that generally when there is only one connection mongoose. connect() is use, whereas if there is multiple instance of connection mongoose. createConnection() is used.

Can Mongoose connect to multiple databases?

Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.


2 Answers

Generally speaking you don't do this. The mindset is a little different with mongoose than working with the native driver in it's raw form, and there are plenty of things helping under the hood to make things work a bit more seamlessly without diving into the gory details.

So the basic approach is when you define your "schema" and "models", these are bound to the default connection instance. Unless you have a specific reason for binding to another connection, this is what you should follow:

So you would have a Schema and model definition:

var mySchema = new Schema({
    "name": String
});

module.exports = mongoose.model( "Model", mySchema, "collection" )

Where the "collection" part is optional otherwise the "model" name in the first argument is put to standard rules, usually lowercase and pluralized.

Then in your other code listing, you pull this in with require:

var Model = require('./models/mymodel.js');

And use your model objects as mongoose permits:

Model.find({ "field": "name"}, function(err,models) {

});

So it allows a bit more abstract handling than is done with the basic driver as the "models" themselves know how to bind to connections, or are otherwise explicitly bound to the connection you want as an optional parameter.

like image 127
Neil Lunn Avatar answered Oct 19 '22 23:10

Neil Lunn


You can create a default Mongoose connection:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');

var db = mongoose.connection;

If you want to open multiple connections you can use createConnection:

var dbconnection = mongoose.createConnection ('uri,uri');

This connection object can then be used for creating/retrieving models that are scoped only to this connection.

The Mongoose connection object has multiple events on which you attach handlers. You should check out the documentation for the full list of handlers you can use.

To get you started, a basic approach would be:

// log connection errors
db.on('error', console.error.bind(console, 'connection error:'));

// wait for opening the connection
db.once('open', function () {
   // do something once connection to the MongoDB is open
});

If you open your connection using createConnection, you need to use it when creating models:

// dbconnection is created using createConnection
var MyModel = dbconnection.model('MyModel', MyModelSchema);
like image 33
Christian P Avatar answered Oct 20 '22 00:10

Christian P