是否可以在猫鼬中相互引用两个模式

Is it possible to reference two schemas to eachother in Mongoose?

本文关键字:引用 模式 两个 是否      更新时间:2023-09-26

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

电子邮件.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);