4

我有两个模式,我希望能够从另一个访问它们。我正在尝试做这样的事情:

//电子邮件.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() 打印空字符串,第二个按预期打印。我觉得我正在尝试在其他模式中获取变量,甚至在它们被创建之前。有没有常见的解决方法?或者我应该在我的设计中避免双重依赖?

4

2 回答 2

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 
}
于 2014-01-14T09:32:58.253 回答
0

您可以定义 Schema Add 语句来描述公共属性:

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}
  }});
};

然后需要将 add 语句放入多个模式定义文件中。

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

var ProductCodeSchema = new Schema({
});
ProductCodeSchema.plugin(productCodePlugin);
于 2014-01-14T09:10:37.797 回答