简体   繁体   English

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

[英]How to insert a long/BigInt with Node.js MongoDB Driver?

I try to insert a long/BigInt into my MongoDB Database with the Node.js Mongo Driver.我尝试使用 Node.js Mongo 驱动程序将long/BigInt插入到我的 MongoDB 数据库中。

I've already tried with BigInt , but it doesn't insert the number (expiry) in the document.我已经尝试过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.

I want it to save as BigInt because we need to get it later with a Java Server.我希望它保存为BigInt,因为我们稍后需要使用 Java Server 获取它。

use Long使用长

https://mongodb.github.io/node-mongodb-native/3.5/api/Long.html 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))
};

BigInt is an object in JS you can't just pass it to Mongodb. BigInt 是 JS 中的一个对象,您不能将它传递给 Mongodb。 Take a look at the data types supported by Mongodb.看一下Mongodb支持的数据类型。

https://docs.mongodb.com/manual/reference/bson-types/ https://docs.mongodb.com/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.我建议将 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM