2013-10-01 1 views
3

У меня есть два Schemas, и я хочу, чтобы иметь возможность получить доступ к обоим из другой .. Я пытаюсь сделать что-то вроде этого:Можно ли ссылаться на две схемы друг на друга в 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); 
Смежные вопросы