skip to Main Content

I’m using Azure Service Bus (@azure/service-bus) in a TypeScript-based nest.js service to schedule messages to be delivered at a future point in time. I need to be able to cancel those messages before the delivery date if needed. My plan was to create messages and schedule them for a delivery date using the scheduleMessages function, which returns an ID of the scheduled message. I would then save the message ID into my mongodb database, so that later on I can pull that back out and use it to cancel the message with the cancelScheduledMessages function which takes that id as a parameter.

However, it seems that the @azure/service-bus package uses it’s own internal Long type for these ids. This type is not exported from the package, so if I convert ids from this Long type to any other type (as I need to in order to store them in my mongo database), I am unable to convert back.

The documentation for the scheduleMessages function has this to say about the ids:

Save the Long type as-is in your application without converting to number. Since JavaScript only supports 53 bit numbers, converting the Long to number will cause loss in precision

Surely there has to be a way for me to save these to a database and use them later? Or does "Save the Long type as-is in your application" mean that I’m just out of luck here? I find it hard to believe that the fine folks making this service bus package would not allow us any flexibility with saving an id like this.

I appreciate any and all suggestions.

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    The Mongo Long type is not compatible with @azure/service-bus, but after looking in the source files of the plugin, I found this comment at the bottom of the Long type definition:

    export = Long; // compatible with `import Long from "long"

    With this, I was able to use this compatible type instead, and save to mongo using the mongoose-long npm package which adds support for the Long type compatible with Long from 'long'.


  2. The short answer:

    const MongoClient = require('mongodb').MongoClient;
    var Long = require('mongodb').Long;
    
    const uri = 'mongodb://testuser:mysecret@localhost:27017,localhost:27018,localhost:27019/?replicaSet=replSet';
    
    
    var document = {'longInteger': Long.fromString("123") };
    
    var dbName = "mydb";
    var collectionName = "mycollection";
    
    const client = new MongoClient(uri, { useUnifiedTopology: true });
    
    var db = client.db(dbName);
    var collection = db.collection(collectionName);
    
    var document = {'someLongValue' : Long.fromString("123")};
    
    collection.insertOne(document, function (err, result) {});
    

    See similar post Node js Mongodb Query NumberLong

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search