簡體   English   中英

Mongoose Schema 類型作為來自 TypeScript 的自定義接口?

[英]Mongoose Schema type as a custom interface from TypeScript?

在此處輸入圖像描述

我想存儲一個具有 StationRating 接口屬性的自定義 object,有人可以幫我嗎?

這是可能的,但它需要一些樣板文件。 問題是:

  • TS 中的接口和類型在發出的代碼中不存在

  • 雖然您可以在另一個方向上使用 go - 創建一個模式 object 並從中創建一個接口/類型 - 模式 object 值必須是構造函數,例如Number ,這不是number的東西。

但是您可以創建一個將構造函數類型映射到其原始類型(例如Numbernumber )的類型,然后使用它將模式 object 轉換為您想要的類型:

type ConstructorMapping<T> =
    T extends NumberConstructor ? number :
    T extends StringConstructor ? string : never; // etc: continue as needed

const schemaObj = {
  score: Number,
  user_id: String,
  station_id: String,
  description: String,
};

type SchemaObj = typeof schemaObj;
type StationRating = {
    [prop in keyof SchemaObj]: ConstructorMapping<SchemaObj[prop]>
};

然后在調用new Schema時使用schemaObj ,您還將擁有以下可用類型:

type StationRating = {
    score: number;
    user_id: string;
    station_id: string;
    description: string;
}

這值得么? 我不確定。 對於較小的物體,也許不是。 對於較大的物體,也許是這樣。 您可能更喜歡只寫出類型和架構 object。

是否有特定原因要將其存儲在 object 中? 您可以使用虛擬方法來創建“評級”。 如果沒有看到更多內容,我不確定,但如果您只想參考分數或根據分數創建一些計算,那么這似乎是一個足夠簡單的解決方案。 https://mongoosejs.com/docs/tutorials/virtuals.html

const userSchema = mongoose.Schema({
  firstName: String,
  lastName: String
});
// Create a virtual property `fullName` with a getter and setter.
userSchema.virtual('fullName').
  get(function() { return `${this.firstName} ${this.lastName}`; }).
  set(function(v) {
    // `v` is the value being set, so use the value to set
    // `firstName` and `lastName`.
    const firstName = v.substring(0, v.indexOf(' '));
    const lastName = v.substring(v.indexOf(' ') + 1);
    this.set({ firstName, lastName });
  });
const User = mongoose.model('User', userSchema);

const doc = new User();
// Vanilla JavaScript assignment triggers the setter
doc.fullName = 'Jean-Luc Picard';

doc.fullName; // 'Jean-Luc Picard'
doc.firstName; // 'Jean-Luc'
doc.lastName; // 'Picard'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM