2013-10-01 54 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

是的,你可以在Mongoose中創建交叉引用。但是在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); 
相關問題