Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I share mongoose models between 2 apps?

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'm running into issues with the fact that once you call mongoose.model('Model', Schema) in app A, they are 'tied' to that app's mongoose/mongodb connection.

Does anyone have any tips on the best way to manage this?

like image 1000
evilcelery Avatar asked Sep 28 '12 00:09

evilcelery


People also ask

What is the difference between Mongoose schema and model?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Can you use Mongoose and MongoDB together?

Connecting to MongoDBMongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose. connect() , as shown below. You can get the default Connection object with mongoose.

Is Mongoose an ORM for MongoDB?

Mongoose is a Node. js-based Object Data Modeling (ODM) library for MongoDB. It is akin to an Object Relational Mapper (ORM) such as SQLAlchemy for traditional SQL databases. The problem that Mongoose aims to solve is allowing developers to enforce a specific schema at the application layer.

Is schema necessary for Mongoose?

Each element of the array is an object with 2 properties: schema and model . This property is typically only useful for plugin authors and advanced users. You do not need to interact with this property at all to use mongoose.


2 Answers

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

like image 77
Nathan Romano Avatar answered Sep 21 '22 05:09

Nathan Romano


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.

like image 37
evilcelery Avatar answered Sep 17 '22 05:09

evilcelery