【问题标题】:How to use an asynchronous default value in mongoose schema?如何在猫鼬模式中使用异步默认值?
【发布时间】:2020-11-01 17:56:31
【问题描述】:

我正在尝试获取一个日期时间并在我的猫鼬模式中使用它,只是因为即使我更改了 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;
      })
    }
  }
});

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 为什么不先得到响应,然后声明架构?
  • @RameshReddy 在这种情况下我应该如何获取数据?
  • 您希望在创建新模型时获取此http://worldtimeapi.org/api/timezone/Asia/Yerevan 还是仅在定义架构时获取?
  • @RameshReddy 我只想使用架构中的 date.datetime 作为默认日期

标签: javascript node.js mongoose promise axios


【解决方案1】:

我不认为模型/模式可以是异步的,但由于您需要一个异步默认值,您可以试试这个:

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);

【讨论】:

  • 这会在使用export const Price = mongoose.model('Prices', pricesSchema); 时导致错误。 pricesSchema is not defined
  • 现在价格模式未定义,它返回 Schema hasn't been registered for model "Prices". 你不能只在承诺中设置外部变量
  • 由于某种原因没有插入日期
  • @Areg 是否在控制台中看到任何错误?尝试删除 if 语句
  • const datetimeundefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-31
  • 1970-01-01
  • 2020-09-27
  • 2020-06-23
  • 2019-12-12
  • 2018-02-27
相关资源
最近更新 更多