2013-10-01 4 views
3

내가 이런 일을하려고하고 .. 내가 두 스키마를 가지고, 내가 다른 하나에서 둘 다에 액세스 할 수 있도록하려면 :Mongoose에서 두 스키마를 서로 참조 할 수 있습니까?

//email.js을

var mongoose = require('mongoose') 
    ,Schema = mongoose.Schema 
    , FoodItemSchema = require('../models/fooditem.js') 
    , UserSchema = require('../models/user.js').schema 
    , User = require('../models/user.js').model 

    console.log(require('../models/user.js')); 

    var emailSchema = new Schema({ 
     From : String, 
     Subject : FoodItemSchema, 
     Body : String, 
     Date: Date, 
     FoodItems : [FoodItemSchema], 
     Owner : { type : Schema.Types.ObjectId , ref: "User" } 
    }); 

    module.exports = { 
     model: mongoose.model('Email', emailSchema), 
     schema : emailSchema 
    } 

//user.js

var mongoose = require('mongoose') 
    ,Schema = mongoose.Schema 
    , Email = require('../models/email.js').model 
    , EmailSchema = require('../models/email.js').schema 


console.log(require('../models/email.js')); 

var userSchema = new Schema({ 
    googleID : String, 
    accessToken : String, 
    email : String, 
    openId: Number, 
    phoneNumber: String, 
    SentEmails : [EmailSchema] 
    // Logs : [{type: Schema.ObjectId, ref: 'events'}] 
}); 
module.exports = { 
    model : mongoose.model('User', userSchema), 
    schema : userSchema 
} 

첫 번째 console.log()는 빈 문자열을 출력하고 두 번째는 예상대로 인쇄합니다. 내가 만든 전에도 다른 스키마에서 변수를 얻으려고하는 것 같습니다. 이에 대한 일반적인 해결 방법이 있습니까? 또는 디자인에서 이중 종속성을 피할 수 있습니까?

답변

5

예, 몽구스에서 상호 참조를 만들 수 있습니다. 그러나 Node.js에 순환 종속성을 만드는 방법은 없습니다. 참조를 만들려면 사용자 스키마를 요구할 필요가 없으므로 필요하지 않습니다.

var mongoose = require('mongoose') 
    , Schema = mongoose.Schema 
    , FoodItemSchema = require('../models/fooditem.js'); 

var emailSchema = new Schema({ 
    From: String, 
    Subject: FoodItemSchema, 
    Body: String, 
    Date: Date, 
    FoodItems: [FoodItemSchema], 
    Owner: { type: Schema.Types.ObjectId , ref: 'User' } 
}); 

module.exports = { 
    model: mongoose.model('Email', emailSchema), 
    schema: emailSchema 
} 
0

당신은 스키마가 공통 속성을 설명하기 위해 문을 추가 정의 할 수 있습니다

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

module.exports = exports = function productCodePlugin(schema, options) { 
    schema.add({productCode:{ 
    productCode : {type : String}, 
    description : {type : String}, 
    allowed : {type : Boolean} 
    }}); 
}; 

는 여러 스키마 정의 파일에 추가 문을 필요로한다.

var mongoose = require('mongoose') 
    , Schema = mongoose.Schema 
    , ObjectId = Schema.ObjectId 
    , productCodePlugin = require('./productCodePlugin'); 

var ProductCodeSchema = new Schema({ 
}); 
ProductCodeSchema.plugin(productCodePlugin); 
관련 문제