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\'
./shared/models/user.js
./app1/app.js
var user = require('../shared/user.js');
./app2/app.js
var user = require('../shared/user.js');
I dont' see why you couldn't just load the models from a shared path.
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);
You have share your mongoose instance around by using doing something like this
var mongoose = require('mongoose');
module.exports.mongoose = mongoose;
var user = require('./lib/user');
Now inside of "lib/user.js"
var mongoose = module.parent.mongoose;
var model = mongoose.model('User', new mongoose.Schema({ ... });
module.exports = model;
So doing it like that you can require "lib/user.js" in other applications
If you want to reuse your Mongoose package between other NPM packages, the best way to do it is to install the shared package at the top level app and then use it to initialize the other NPM packages.
You can use this npm module: https://www.npmjs.com/package/mongoose-global
What I ended up doing here was importing app1 as a submodule (with Git) in app2. This way the models can be imported as normal and are tied to the app's default mongoose
connection.
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);