如何在猫鼬中使用混合数据类型限制值? [英] How to restrict values using Mixed data type in Mongoose?

查看:31
本文介绍了如何在猫鼬中使用混合数据类型限制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mongoose.jsnode.js.我有一个猫鼬模式,如下所示.

I am using mongoose.js with node.js. I have a mongoose schema as shown below.

myModel: {
     type: Schema.Types.Mixed,
}

我想将架构中的值限制为预定义的类型值String 其中我的键应该是动态的.

I want to restrict the values in the schema to predefined values of type String where as my keys should be dynamic.

例如

 myModel: {
     "Dynamic Key 1" : "Restricted value 1",
     "Dynamic Key 2" : "Restricted value 2",
     "Dynamic Key 3" : "Restricted value 3"
 }

其中我的值必须接受 Restricted value 1Restricted value 2Restricted value 3 只允许键接受任何没有任何限制的东西.

where my values must accept Restricted value 1, Restricted value 2 and Restricted value 3 only allowing keys to accept anything without any restrictions.

Schema.Types.Mixed 是在这里使用的正确类型吗?如果没有,最好的方法是什么?

Is Schema.Types.Mixed the right type to be used here? If not, what is the best approach?

推荐答案

如果可能,最好避免使用动态键,因为它们会使一切变得更加困难.不使用 Mixed,而是通过使 myModel 成为一个包含动态 key value 和使用 enum 验证的字符串 value 字段:

It's best to avoid dynamic keys if possible as they make everything harder. Instead of using Mixed, give the field more structure by making myModel an array that contains a dynamic key value and a string value field that's validated using enum:

myModel: [{
    key: String,
    value: {
        type: String, 
        enum: ['Restricted value 1', 'Restricted value 2', 'Restricted value 3']
    }
}]

您的示例文档将变为:

myModel: [
    { key: "Dynamic Key 1", value: "Restricted value 1" },
    { key: "Dynamic Key 2", value: "Restricted value 2" },
    { key: "Dynamic Key 3", value: "Restricted value 3" }
]

这篇关于如何在猫鼬中使用混合数据类型限制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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