skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

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


  2. Just use

    blockTime: new Date()
    

    Mondodb will intelligently handle the rest.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search