如何使用Node.js MongoDB驱动程序插入长/大整数?

4

我试图使用Node.js的Mongo驱动将long/BigInt插入到我的MongoDB数据库中。

我已经尝试使用BigInt,但它无法将数字(到期日)插入到文档中。

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

我希望它保存为BigInt,因为我们需要在Java服务器上获取它。

2个回答

3
BigInt是JS中的一个对象,你不能直接将它传递给Mongodb。请查看Mongodb支持的数据类型。

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

我建议在mongodb中将BigInt存储为字符串,让读取器在读取文档时解析它。
// 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);

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接