Jithin Ks
Jithin Ks

Reputation: 529

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

Upvotes: 3

Views: 4973

Answers (2)

Cao Shouguang
Cao Shouguang

Reputation: 148

Just use

blockTime: new Date()

Mondodb will intelligently handle the rest.

Upvotes: 0

Jithin Ks
Jithin Ks

Reputation: 529

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

Upvotes: 1

Related Questions