How can I share mongoose models between 2 apps?

后端 未结 6 516
不思量自难忘°
不思量自难忘° 2021-02-04 06:26

I have 2 apps, each in a different folder and they need to share the same models.

I want to symlink the models folder from app A to a models folder in app B.

I\'

6条回答
  •  我在风中等你
    2021-02-04 07:05

    My approach to sharing Mongoose models is to pass the mongoose object in as an argument to the shared module that defines the schemas and creates the models. So the file with the shared schemas/models looks like this:

    module.exports = function(mongoose) {
    
        var packageSchema = new mongoose.Schema({
            title:          { type: String, required: true },
            description:    String
        });
    
        mongoose.model('Package', packageSchema, 'packages');
    };
    

    and then each project requires them in like this:

    var mongoose = require('mongoose');
    var mongo_url = process.env.MONGO_CONNECTION;
    mongoose.Promise = global.Promise;
    
    mongoose.connect(mongo_url, connectOpts);
    require('../../../shared/models/packages')(mongoose);
    

提交回复
热议问题