user3060636
user3060636

Reputation: 272

mongoose - possible circular dependency?

I have the following mongoose models in my express app:

//dog.js
var mongoose = require("mongoose");

var dogSchema = (exports.dogSchema = mongoose.Schema({
  name: { type: String, required: true },
}));

Then I import dog.js to my user.js

//user.js
var mongoose = require("mongoose");
var dog = require("./dog");

var userSchema = mongoose.Schema({
  user: { type: String, required: true },
  pass: { type: String, required: true },
  dogs: [dog.dogSchema],
});

Now, from my routes I am creating a new user like this:

var user = require("../models/user");
var dog = require("../models/dog");

dog = new dog.Dog(dogData);
user = new user.User(data); //this will of course contain also dogData
user.save(next);

Is this the correct way to do this kind of operation? I have the feeling that I might be generating a circular dependency somehow, and anyway it does not look right to me. Any ideas on how to create sub-documents where the schema is from another model file?

Upvotes: 1

Views: 9410

Answers (1)

Daniel Flippance
Daniel Flippance

Reputation: 7932

You can create simultaneous references in two directions without creating circular problems. Create a reference from one document to the other using ref. From the docs:

http://mongoosejs.com/docs/populate.html

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

Then you can then choose to load the sub document using populate

Story.find({ --your criteria-- })
    .populate('_creator')
    .exec(function (err, story) {../});

You can then store the 2 schemas in separate .js files and require them both

Upvotes: 6

Related Questions