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
Apparently, the type of the blockTime should be Date instead of Number, when I changed the type to Date, it worked
Just use
Mondodb will intelligently handle the rest.