4

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.

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

use Long

https://mongodb.github.io/node-mongodb-native/3.5/api/Long.html

const { Long } = require('mongodb');
let expire = BigInt(parseInt((Date.now() / 1000) + 21600, 10));
let newDoc = {
    type: "group.test",
    expiry: new Long(Number(expire & 0xFFFFFFFFn), Number((expire >> 32n) & 0xFFFFFFFFn))
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.