简体   繁体   中英

How to use an asynchronous default value in mongoose schema?

I am trying to fetch a datetime and use it in my mongoose schema, just because the server returns wrong timezone even though i changed the settings on heroku. I am trying to set the default date on schema by using axios request. But it doesn't work because its a promise. Is there any way i can somehow extract the value out? I have looked everywhere but all of them use callbacks but i dont think if i can do that in here.

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

Any help will be very appreciated, thank you.

I don't think models/schemas can be async but since you need an asynchronous default value you can try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM