访问架构默认值

Accessing schema default values

我已经为我的数据库定义并导出了一个带有一些默认值的模式。如何从另一个模块访问模式的默认值?

const mySchema = new Schema({
    property: {
         type: String,
         enum: ['a', 'b', 'c', ...]
    },
    ...
});

module.exports = mongoose.model('Alpha', mySchema);

例如,我想遍历枚举数组值和 console.log(array[i]).

let alphabet = mySchema.property.enum
alphabet.forEach(letter => console.log(letter))

可以从 mongoose 模式本身访问 默认 enum 值。您需要将 enums 存储在一个单独的变量中并在您的模型中使用它。然后导出该变量并在需要的地方使用它。

export enum PropertyEnums {
  a = "a", // set value of enum a to "a" else it will default to 0
  b = "b",
  c = "c",
  ...
}

const mySchema = new Schema({
    property: {
         type: String,
         enum: Object.values(PropertyEnums), // equivalent to ["a", "b", "c", ...]
         default: PropertyEnums.a // if you want to set a default value for this field
    },
    ...
});

module.exports = mongoose.model('Alpha', mySchema);

然后像这样在需要的地方导入枚举:

import { PropertyEnums } from "./yourSchemaFile.js"

let alphabet = Object.values(PropertyEnums)
alphabet.forEach(letter => console.log(letter))

您可以像下面这样定义:

export enum Props {
  A = 'A',
  B = 'B'
}

架构中:

property: {
     type: String,
     enum: Props
},

访问权限:

for (let item in Props) {
  if (isNaN(Number(item))) {
    console.log(item);
    }
}