mongoose - possible circular dependency?

后端 未结 1 726
滥情空心
滥情空心 2021-01-23 15:00

I have the following mongoose models in my express app:

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

var userSchema = mo         


        
相关标签:
1条回答
  • 2021-01-23 15:31

    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

    0 讨论(0)
提交回复
热议问题