PaolaJ.
PaolaJ.

Reputation: 11532

How to reconnect mongoose to another remote server?

I am totally new to node.js and mongoose, how to reconnect mongoose to another remote server ? At the beginning of the file I have

var mongoose = require('mongoose')

and connected to localhost,

later in code I have

var uristring ='mongodb://remote_server/db';
var mongoOptions = { db: { safe: true } };

// Connect to Database
mongoose.createConnection(uristring, mongoOptions, function (err, res) {
    if (err) {
        console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
    } else {
        console.log ('Successfully connected to: remote' + uristring);
    }
});

and I always get Successfully connected to: remote but when I bellow that print look for document by id I get always from local database(I have schema imported like require Person = mongoose.model('Person');). How to reconnect to remote if I already have connection to local.

Upvotes: 0

Views: 1225

Answers (1)

durum
durum

Reputation: 3404

There are two ways of initializate a connection in mongoose:

  1. Using the default connection "object"
  2. Creating a connection from the dust

Here you are creating a connection, but using a model from another. Models are tied to databases (normal databases, replica sets or clusters) so you're not accesing to the correct host.

You must use the default connection (using mongoose.connect instead of mongoose.createConnection) or create a model in that new connection you are using. In your example:

  var uristring ='mongodb://remote_server/db';
  var mongoOptions = { db: { safe: true } };

  // Connect to Database
  var newConnection = mongoose.createConnection(uristring, mongoOptions);

  newConnection.model(/*whatever*/);

mongoose.model wires to mongoose.connection. That is not the new connection you have created.

Upvotes: 2

Related Questions