最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to insert a longBigInt with Node.js MongoDB Driver? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Sep 4, 2019 at 3:45 SuperStar518 2,8952 gold badges21 silver badges37 bronze badges asked Sep 4, 2019 at 1:00 SchdowSchdow 451 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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./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);

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))
};
发布评论

评论列表(0)

  1. 暂无评论