Hi. I’m executing a function that makes an api call and saves the result on a collection. My problem is that even tho the schema has one field defined as Long(Int64) it saves the numbers there as Double. How to I make sure it’s saved properly?

Thanks

I’m having the same problem here.

The only current solution I have found is to save as int32 by writing something like

atlasField: longValueFromApi | 0

Hi, this is actually a generic Javascript problem (integers don’t really exist). In general, the best approach is to use the BSON library in the driver to wrap any numbers in the specific type. Please see here for more detail: https://www.mongodb.com/docs/atlas/app-services/functions/globals/#std-label-bson-long

I tried, but there isn’t a way to just save that number into a long int64, it requires conversion to low 32 and high 32 and I’ve tried looking for what that means and I come up blank. Is there any examples of direct conversion or documentation on how to do that?

Please see here for details on the BSON package: Long() — MongoDB Node.JS Driver 1.4.9 documentation

This is what I get

{"message":"'Long' is not defined","name":"ReferenceError"}

Hi, I just tested this out and it seems to be working for me.

exports = async function(arg){
  var serviceName = "mongodb-atlas";
  var dbName = "test";
  var collName = "dog";

  // Get a collection from the context
  var collection = context.services.get(serviceName).db(dbName).collection(collName);

  intAge = BSON.Long(10, 0)
  await collection.insertOne({age: intAge})
};

Let me know if this is not working for you.

Hi. Thanks for the example, but it doesn’t work.


Screenshot 2024-04-25 at 3.23.11 PM
Granted, the number IS int64, but it’s a totally different number

Yup, that looks like what would happen if there is overflow (you are sending something overflowing an int32 into the constructor). The driver has BSON.Long.fromNumber() but it would seem that is not supported in the functions runtime.

I would look at the code in the driver and adopt it to your needs if you expect to overflow the maximum int32 value: js-bson/src/long.ts at c58d1e213714c99bbb09d0f91a3c9199e43710dd · mongodb/js-bson · GitHub

Hi. I tried but failed, I’m not an expert in JS, much less TS but I thought this would work