亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在貓鼬模式中使用異步默認值?

如何在貓鼬模式中使用異步默認值?

aluckdog 2022-11-11 16:59:00
我試圖獲取一個日期時間并在我的貓鼬模式中使用它,只是因為服務器返回了錯誤的時區,即使我更改了 heroku 上的設置。我正在嘗試使用 axios 請求在架構上設置默認日期。但它不起作用,因為它是一個承諾。有什么辦法可以讓我以某種方式提取價值嗎?我到處找,但他們都使用回調,但我不認為我可以在這里做到這一點。var pricesSchema = mongoose.Schema({  USD_LOWEST: {    type: Number,    required: true  },  USD_LOW: {    type: Number,    required: true  },  USD_HIGH: {    type: Number,    required: true  },  USD_HIGHEST: {    type: Number,    required: true  },  USD_CBA: {    type: Number,    required: true  },  BTC_PRICE: {    type: Number,    required: true  },  date: {    type: String,    default : function(){      axios.get('http://worldtimeapi.org/api/timezone/Asia/Yerevan').then(data=>{        return data.datetime;      })    }  }});任何幫助將不勝感激,謝謝。
查看完整描述

1 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

我不認為模型/模式可以是異步的,但由于您需要一個異步默認值,您可以試試這個:


const pricesSchema = mongoose.Schema({

  USD_LOWEST: {

    type: Number,

    required: true,

  },

  USD_LOW: {

    type: Number,

    required: true,

  },

  USD_HIGH: {

    type: Number,

    required: true,

  },

  USD_HIGHEST: {

    type: Number,

    required: true,

  },

  USD_CBA: {

    type: Number,

    required: true,

  },

  BTC_PRICE: {

    type: Number,

    required: true,

  },

  date: {

    type: Date,

    expires: 60 * 60 * 24 * 7,

  },

});



pricesSchema.pre('save', async function () {

  if (!this.date) {

    const response = await axios.get('http://worldtimeapi.org/api/timezone/Asia/Yerevan');

    this.date = response.data.datetime;

  }

});


export const Price = mongoose.model('Prices', pricesSchema);


查看完整回答
反對 回復 2022-11-11
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號