【问题标题】:How to insert a long/BigInt with Node.js MongoDB Driver?如何使用 Node.js MongoDB 驱动程序插入 long/BigInt?
【发布时间】:2019-09-04 01:00:41
【问题描述】:

我尝试使用 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 服务器来获取它。

【问题讨论】:

    标签: javascript node.js mongodb object


    【解决方案1】:

    用长线

    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))
    };
    

    【讨论】:

      【解决方案2】:

      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 2013-04-03
        • 2016-11-09
        • 1970-01-01
        • 2018-05-24
        • 2016-09-20
        相关资源
        最近更新 更多