可以在Mongoose中相互引用两个模式吗? [英] Is it possible to reference two schemas to eachother in Mongoose?

查看:108
本文介绍了可以在Mongoose中相互引用两个模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two Schemas, and I want to be able to access both of them from the other one.. I am trying to do something like this:

/ /email.js

//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

//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()打印空字符串,第二个打印出预期的字符串。我觉得我试图在创建其他模式之前尝试获取变量。这有一个共同的解决方法吗?或者我应该避免在我的设计中出现双重依赖?

The first console.log() prints empty string and the second one prints as expected. I feel like I am trying to get the variables in the other schema even before they were created. Is there a common workaround for this? Or should I avoid double dependencies in my design?

推荐答案

是的,您可以在Mongoose中创建交叉引用。但是没有办法在Node.js中创建循环依赖。但是,您不需要,因为不需要用户模式来创建引用:

Yes, you can create cross-references in Mongoose. But there is no way to create cyclic dependencies in Node.js. Though, you don't need to, because there is no need to require user schema in order to create a reference:

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 
}

这篇关于可以在Mongoose中相互引用两个模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆