3

In following project structure I have a dependency between 2 custom MEAN.IO packages

/custom

  • package1
    • server
      • controllers
      • routes
      • models
        • model1.js
  • package2
    • server
      • controllers
      • routes
      • models
        • model2.js

model1 and model2 are both used in their own controllers, but I would like to implement an algorithm which uses both.

My first guess would be:

var Model2 = mongoose.model('Model2')

But this returns an error:

MissingSchemaError: Schema hasn't been registered for model "Model2".

My second guess was to include model again:

var model = require('../../../package2/server/models/model2'),
Meeting = mongoose.model('Meeting'), ...

Yet still no luck, is there anybody who knows how to include models from another package in mean.io?

emiel187
  • 191
  • 2
  • 3
  • 9
  • You can do it the way article is using user model. https://github.com/linnovate/mean/blob/master/packages/core/articles/server/models/article.js – Vikram Tiwari Aug 05 '15 at 08:37
  • 2
    The article controller does not include the User model, it just populates the 'user' field. – emiel187 Aug 05 '15 at 09:32

2 Answers2

0

Yes you can.

Each of the model object is handled by mongoose, and since mongoose is global, you can just call a schema of it.

You have to add your model to mongoose using mongoose.model(modelName, schema)

in your model.js do

var mongoose  = require('mongoose'),
Schema    = mongoose.Schema,
crypto    = require('crypto'),
      _   = require('lodash');
var Model1Schema = new Schema({ ... });
mongoose.model('Model1', ModelSchema);

in your controller you can call it this way

var mongoose = require('mongoose'),
Model1 = mongoose.model('Model1'),
_ = require('lodash');

check for more here http://mongoosejs.com/docs/guide.html

  • 1
    The problem is with MEAN.IO, not with mongoose. I registered the schema's correctly in my models, but they were not loaded at the right time. – emiel187 Aug 06 '15 at 08:52
0

Yeah it seems that Model2 hasn't been initialized by the time

var Model2 = mongoose.model('Model2')

was executed. I think mean.io is loading the packages alphabetically that's why Model2 hasn't been loaded during Model1's initialization. What you can do as a work around is to use

mongoose.model('Model2')

in your model functions repeatedly instead of putting it in a variable.

An example would be

Model1Schema.statics.findUsingModel2 = function(model2Id,cb){
    mongoose.model('Model2').find({_id : model2Id}).exec(cb);
}
fflajom
  • 39
  • 4