【问题标题】:defining 2 types under 1 variable in mongodb在 mongodb 中的 1 个变量下定义 2 种类型
【发布时间】:2021-05-04 01:17:44
【问题描述】:

我正在尝试创建一个如下所示的架构:

const exampleSchema = mongoose.Schema({
    topic: {
         type: String,
         required: true,
    },
    words: {
         type: String || Array: {
              type: String,
              required: true,
             }
         required: true,
     }
});

我已经阅读了 mongodb 中的自定义类型,但不明白文档向我展示的内容。谁能帮帮我?

【问题讨论】:

  • 这能回答你的问题吗? Boolean and Number in Schema (Mongoose)
  • 遗憾的是,但这对我来说太复杂了。我不明白如何创建它,也不知道它是如何工作的。我编辑了我的问题,希望有人可以帮助我!

标签: javascript database mongodb mongoose


【解决方案1】:

在猫鼬中创建custom schema

class StringOrArray extends mongoose.SchemaType {
    constructor(key, options) {
        super(key, options, 'StringOrArray');
    }

    cast(val) {
        // please change your logic as per your requirement
        if (typeof val !== 'string' && !Array.isArray(val)) {
            throw new Error('StringOrArray: ' + val + ' must be a String or Array');
        }
        return val;
    }
}

// Don't forget to add `Int8` to the type registry
mongoose.Schema.Types.StringOrArray = StringOrArray;

在您的架构中使用 StringOrArray

const exampleSchema = mongoose.Schema({
    topic: {
        type: String,
        required: true,
    },
    words: {
        type: StringOrArray,
        required: true
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2023-03-11
    • 2022-11-15
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多