Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a long/BigInt with Node.js MongoDB Driver?

I try to insert a long/BigInt into my MongoDB Database with the Node.js Mongo Driver.

I've already tried with BigInt, but it doesn't insert the number (expiry) in the document.

let expire = BigInt(parseInt((Date.now() / 1000) + 21600, 10));
let newDoc = {
    type: "group.test",
    expiry: expire
};
collection.insertOne(newDoc);
// it only inserts the type.

I want it to save as BigInt because we need to get it later with a Java Server.

like image 511
Schdow Avatar asked Sep 20 '25 01:09

Schdow


1 Answers

BigInt is an object in JS you can't just pass it to Mongodb. Take a look at the data types supported by Mongodb.

https://docs.mongodb.com/manual/reference/bson-types/

I would suggest storing the BigInt as string in mongodb and let the reader parse it when the document is read.

// Note: this function is a simple serializer
// meant to demo the concept.
function bigIntSerializer(num){
  return {
    type: "BigInt",
    value: num.toString()
  };
}

let expire = BigInt(parseInt((Date.now() / 1000) + 21600, 10));
let newDoc = {
    type: "group.test",
    expiry: bigIntSerializer(expire)
};
collection.insertOne(newDoc);
like image 97
Josnidhin Avatar answered Sep 22 '25 15:09

Josnidhin