Load models from other packages to MEAN.IO

In the following project structure, I have a dependency between two custom MEAN.IO packages

/ custom

  • package1
    • Server
      • Controllers
      • routes
      • model
        • model1.js
  • package2
    • Server
      • Controllers
      • routes
      • model
        • model2.js

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

My first guess:

var Model2 = mongoose.model('Model2')

      

But this returns an error:

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

      

My second guess was to re-enable the model:

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

      

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

+3


source to share


2 answers


Yes, you can.

Each model object is handled by mongoose, and since mongoose is global, you can simply call its schema.

You have to add your model to mongoose with 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 more here http://mongoosejs.com/docs/guide.html

0


source


Yes, it seems that Model2 has not been initialized by the time

var Model2 = mongoose.model('Model2')

      

... I think mean.io is loading packages alphabetically, why is Model2 not loading during Model1 initialization. What you can do as work is use

mongoose.model('Model2')

      



in your model multiple times instead of placing it in a variable.

An example would be

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

      

0


source







All Articles