SchemaTypeOptions


SchemaTypeOptions()

Type
  • «建構子»

在 schema type 上定義的選項。

範例

const schema = new Schema({ name: String });
schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true

SchemaTypeOptions.prototype.cast

Type
  • «String»

允許覆寫此個別路徑的轉換邏輯。如果是字串,則給定的字串會覆寫 Mongoose 的預設轉換錯誤訊息。

範例

const schema = new Schema({
  num: {
    type: Number,
    cast: '{VALUE} is not a valid number'
  }
});

// Throws 'CastError: "bad" is not a valid number'
schema.path('num').cast('bad');

const Model = mongoose.model('Test', schema);
const doc = new Model({ num: 'fail' });
const err = doc.validateSync();

err.errors['num']; // 'CastError: "fail" is not a valid number'

SchemaTypeOptions.prototype.default

Type
  • «Function|Any»

此路徑的預設值。如果是函式,Mongoose 會執行該函式,並將傳回值用作預設值。


SchemaTypeOptions.prototype.immutable

Type
  • «Function|Boolean»

如果為真值,Mongoose 會禁止在文件第一次儲存到資料庫後,對此路徑進行變更。請在這裡閱讀更多關於 Mongoose 中不可變屬性的資訊。


SchemaTypeOptions.prototype.index

Type
  • «Boolean|Number|Object»

如果為真值,Mongoose 會在編譯模型時在此路徑上建立索引。


SchemaTypeOptions.prototype.ref

Type
  • «Function|String»

如果填充此路徑,則 populate() 應該使用的模型。


SchemaTypeOptions.prototype.ref

Type
  • «Function|String»

populate() 應該用來尋找要使用的模型的路徑。


SchemaTypeOptions.prototype.required

Type
  • «Function|Boolean»

如果為 true,則將 required 驗證器附加到此路徑,以確保此路徑不能設定為 nullish 值。如果是函式,Mongoose 會呼叫該函式,且僅在函式傳回真值時檢查 nullish 值。


SchemaTypeOptions.prototype.select

Type
  • «Boolean|Number»

使用 find()findOne() 等載入文件時,預設要包含或排除此路徑。


SchemaTypeOptions.prototype.sparse

Type
  • «Boolean|Number»

如果為真值,Mongoose 會在此路徑上建立稀疏索引。


SchemaTypeOptions.prototype.text

Type
  • «Boolean|Number|Object»

如果為真值,Mongoose 會在此路徑上建立文字索引。


SchemaTypeOptions.prototype.transform

Type
  • «Function»

為此個別 schema type 定義轉換函式。僅在呼叫 toJSON()toObject() 時呼叫。

範例

const schema = Schema({
  myDate: {
    type: Date,
    transform: v => v.getFullYear()
  }
});
const Model = mongoose.model('Test', schema);

const doc = new Model({ myDate: new Date('2019/06/01') });
doc.myDate instanceof Date; // true

const res = doc.toObject({ transform: true });
res.myDate; // 2019

SchemaTypeOptions.prototype.type

Type
  • «Function|String|Object»

要將此路徑轉換成的類型。


SchemaTypeOptions.prototype.unique

Type
  • «Boolean|Number»

如果為真值,Mongoose 會在編譯模型時在此路徑上建立唯一索引。 unique 選項不是驗證器


SchemaTypeOptions.prototype.validate

Type
  • «Function|Object»

描述如何驗證此 schema type 的函式或物件。