javascript - 如何使用 Node.js MongoDB 驱动程序插入 long/BigInt?

标签 javascript node.js mongodb object

我尝试使用 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);

关于javascript - 如何使用 Node.js MongoDB 驱动程序插入 long/BigInt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57780241/

相关文章:

javascript - 如何覆盖 Sencha Touch 数据存储代理异常监听器?

node.js - 性能: findAndUpdate VS direct save and remove duplicates

arrays - MongoDB 尝试删除数组项时出错

javascript - 如何以百分比形式接收图像的值

JavaScript,检测鼠标光标何时不在任何元素上

javascript - Mocha js 调用 After() 太快了吗?

node.js - nodemon + express,监听端口=?

node.js - 在 express js 中请求同一服务器上的端点

windows - 如何在 Windows 上安装 mongoDB?

javascript - 如何在 v-if 条件下使用 Vue.js 变量/参数