sharing db connection across entire app in mongoose

后端 未结 1 936
一生所求
一生所求 2021-02-11 03:13

With the latest mongoose update, you can no longer user models the way I\'ve been doing. I need to share the same db connection across my entire app.

https://github.com/

相关标签:
1条回答
  • 2021-02-11 04:03

    Option 1: Use a shared object

    My model code looks similar, but instead of repeatedly requiring the modules I just require them once when the application starts and then assign the results to a shared object. For example if you are using an express app you could just so something like app.locals.models.User = require('./models/user');. Then anything with access to the app can see your models without needing a require.


    Option 2: Ensure a single modification in the exported function

    You can define your user module like so:

    var mongoose = require('mongoose');
    
    var userSchema = new mongoose.Schema({name: String});
    
    var User = null;
    
    module.exports = function(db) {
      if (db && User === null) {
        User = db.model('User', userSchema);
      }
      return User;
    };
    

    When you start your application you simply need to: require('./models/user')(db). Subsequent requires by other modules in your application can drop the db paramater, as User will only be set once.

    0 讨论(0)
提交回复
热议问题