Anton Stafeyev
Anton Stafeyev

Reputation: 841

Mongoose saving

model.save() confuses me a lot.

Example. i moved my mongoose.model(mongoose.schema) in separate model.js file. when i create models using this method the following bothers me.

How does save method find a connection which i established with db. Seconds if i have 2 instances of mondogDB connections, which one it picks ?

here is the schema

const Schema = require("mongoose").Schema;
const mongoose = require("mongoose");

   const User = new Schema({
   name: String, 
   password: String, 

   date_created: {
      type: Date,
      default: Date.now
   },

   authorized: {
      type: Boolean,
      default: false
   } 
});

module.exports = mongoose.model("User", User);

Upvotes: 1

Views: 221

Answers (1)

Paul
Paul

Reputation: 36349

So, the output of mongoose.model() is a model, and a given model is always tied to one connection.

By default, most folks just use the connection and connection pooling available from mongoose.connect(). Once you call that, the cached mongoose module is using a singleton connection object under the hood. So for example, if I'm calling your model, I'd do this:

const mongoose = require('mongoose');
const User = require('./models/user');

mongoose.connect(); // or pass in a custom URL

// from here, User will default to the mongoose-internal connection created in the previous line

If I want to use multiple connections, I cannot use the mongoose internal singleton, so I would have to do the operations with the created connection. For example:

// ./schemas/user.js
// You now export the Schema rather than the module in your file
//module.exports = mongoose.model('User', User);
module.exports = User;

Then in the calling code:

const config = require('./config'); // presumably this has a couple mongo URLs
const mongoose = require('mongoose');
const UserSchema = require('./schemas/user');

const conn1 = mongoose.createConnection(config.url1);
const conn2 = mongoose.createConnection(config.url2);

const User1 = conn1.model('User', UserSchema);
const User2 = conn2.model('User', UserSchema);

// now any users created with User1 will save to the first db, users created with User2 will save to the second. 

Upvotes: 1

Related Questions