如何在 Moongoose 模式中实现 OR 运算符?

问题描述 投票:0回答:1

我目前正在 Node 中开发一个网站构建器,用户可以添加不同类型的自定义组件来构建网站。

我的猫鼬模型有问题,我试图将网站定义为一组不同组件,每个组件可以是 3 种不同类型之一(即 OR 运算符)

我正在尝试使用原生js ||密钥但它不起作用,我无法在网上找到有效的解决方案

请参阅下面的我的代码,将多个不同的架构组合成顶级网站架构

const mongoose = require("mongoose");

const headingSchema = new mongoose.Schema({
  type: {
    type: String,
    required: true,
  },
  componentId: {
    type: String,
    required: true,
  },
  details: {
    content: { type: String, required: true },
    fontSize: { type: String, required: true },
    fontType: { type: String, required: true },
    color: { type: String, required: true },
  },
});

const textSchema = new mongoose.Schema({
  type: {
    type: String,
    required: true,
  },
  componentId: {
    type: String,
    required: true,
  },
  details: {
    content: { type: String, required: true },
    lineHeight: { type: String, required: true },
    fontType: { type: String, required: true },
    color: { type: String, required: true },
  },
});

const imageSchema = new mongoose.Schema({
  type: {
    type: String,
    required: true,
  },
  componentId: {
    type: String,
    required: true,
  },
  details: {
    imageName: { type: String, required: true },
    imageUrl: { type: String, required: true },
    width: { type: String, required: true },
  },
});

const websiteSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  owner: {
    type: String,
    required: true,
  },
  components: {
    type: [headingSchema || textSchema || imageSchema],
    required: true,
  },
});

module.exports = mongoose.model("Website", websiteSchema);

任何提示将不胜感激,谢谢

javascript node.js mongodb mongoose mongoose-schema
1个回答
0
投票

执行此操作的一种方法是使用Mixed类型,如下所示:

const websiteSchema = new mongoose.Schema({
  ...
  components: {
    type: mongoose.Schema.Types.Mixed,
    required: true,
  },
});

但这意味着,

components
可以接受任何值,而不一定是
headingSchema | textSchema | imageSchema

© www.soinside.com 2019 - 2024. All rights reserved.