我尝试使用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 服务器获取它。
BigInt 是 JS 中的一个对象,你不能只把它传递给 Mongodb。看看Mongodb支持的数据类型。
https://docs.mongodb.com/manual/reference/bson-types/
我建议将 BigInt 存储为 mongodb 中的字符串,并让读者在阅读文档时解析它。
// 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);
使用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))
};