是否可以在猫鼬中相互引用两个模式
Is it possible to reference two schemas to eachother in Mongoose?
我有两个模式,我希望能够从另一个模式访问它们。我正在尝试做这样的事情:
电子邮件.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
}
用户.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() 打印空字符串,第二个按预期打印。我觉得我甚至在创建变量之前就试图在另一个架构中获取变量。是否有常见的解决方法?还是应该避免设计中的双重依赖关系?
是的,您可以在猫鼬中创建交叉引用。但是没有办法在 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
}
您可以定义 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);
相关文章:
- 如何通过向用户推送模式引用来更新用户对象's数组字段
- 我应该如何在JS中使用揭示模块模式,传递引用,并避免加载顺序问题
- 当链接中引用视频时,是否可以在iPad上以全屏模式打开.mp4
- 单个模式数组中的多个模式引用 - 猫鼬
- 是否可以在猫鼬中相互引用两个模式
- 在单例模式中引用变量的根父级
- 以严格模式在未知环境中获取对全局对象的引用
- 此模式是否会导致闭包中出现循环引用
- 引用Mongoose中的另一个模式
- Javascript模式:引用"this"在私人和公共场合
- JavaScript内置语言特性或API函数在严格模式下引用undefined属性时返回undefined
- Javascript:使用"模块模式"引用变量,有什么想法吗?
- 在Backbone中保存对全局集合的引用的最佳模式
- 如何在Twitter Bootstrap's弹出模式中引用html表单字段?
- javascript正则表达式模式的反向引用
- Javascript模块模式未捕获的引用错误
- 我似乎不能引用2模式填充之后
- 引用对象实例的React.js模式
- Javascript regexp:在反向引用模式中使用变量
- 使用angular显示被引用模式的信息