'How to get BSON UTC datetime value in Node / Javascript?

I'm trying to save an entry in a MongoDB time series collection, but I'm unable to store the timeField correctly, mongo is throwing the error. MongoServerError: 'blockTime' must be present and contain a valid BSON UTC datetime value How can I convert a Date object to a BSON UTC date time?

Below is the schema

import mongoose from "mongoose";

const tradeSchema = new mongoose.Schema(
  {
    blockTime: {
      type: Number,
    },
  },
  {
    timeseries: {
      timeField: "blockTime",
    },
  }
);

const Trade = mongoose.model("trade", tradeSchema);

export default Trade;

Below is the code that is generating the error

const newTrade = new Trade({
  blockTime: new Date().valueOf(),
});

await newTrade.save();


Solution 1:[1]

Apparently, the type of the blockTime should be Date instead of Number, when I changed the type to Date, it worked

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1