How can I share mongoose models between 2 apps?

后端 未结 6 579
不思量自难忘°
不思量自难忘° 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条回答
  •  Happy的楠姐
    2021-02-04 06:52

    One approach is to abstract the Schema into a plain JavaScript object, and then import that object to use to construct the models within your apps.

    For instance, for a 'product' schema:

    www/app1/ProductConfig.js

    const ProductConfig = {
      name: String,
      cost: Number
    }
    module.exports = ProductConfig;
    

    www/app1/ProductSchema.js

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const ProductConfig = require('./ProductConfig');
    
    const Product = new Schema(Product);
    
    module.exports = mongoose.model('Product', Product);
    

    www/app2/ProductSchema.js

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const ProductConfig = require('../app1/ProductConfig');
    
    const Product = new Schema(Product);
    
    module.exports = mongoose.model('Product', Product);
    

提交回复
热议问题