我已經為我的資料庫定義并匯出了一個帶有一些默認值的模式。如何從另一個模塊訪問架構的默認值?
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))
uj5u.com熱心網友回復:
無法從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))
uj5u.com熱心網友回復:
您可以定義如下:
export enum Props {
A = 'A',
B = 'B'
}
在架構中:
property: {
type: String,
enum: Props
},
訪問:
for (let item in Props) {
if (isNaN(Number(item))) {
console.log(item);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465388.html
標籤:javascript 节点.js 表示 猫鼬 猫鼬模式
上一篇:在MongoDB(NodeJS)中選擇具有條件的兩個欄位的不同組合
下一篇:是否可以洗掉陣列中的第一個元素?
