What is the best way to save Azure Service Bus Message IDs with a package-internal type of 'Long' in MongoDB?

Currently, I am utilizing Azure Service Bus (@azure/service-bus) within a TypeScript-based nest.js service to schedule messages for delivery at a future date. In case the need arises, I must also have the ability to cancel these scheduled messages before their intended delivery time. My initial strategy was to create messages and set them up for delivery using the scheduleMessages function, which would return an ID specific to each scheduled message. Subsequently, I planned to store this message ID in my mongodb database, allowing me to retrieve it later when required for cancellation through the cancelScheduledMessages function that accepts the ID as a parameter.

However, it appears that the @azure/service-bus package utilizes its own internal Long type for these IDs. Since this particular type is not readily accessible outside of the package, any attempts on my end to convert these IDs from the Long type to another data type (which is necessary to store them in mongoDB) result in irreversible conversion errors.

The documentation related to the scheduleMessages function provides insight into handling these IDs:

Save the Long type as-is in your application without converting it to a number. Attempting to convert the Long type to a number may lead to loss in precision due to JavaScript's limitation to 53-bit numbers.

Is there a feasible method available for saving these IDs to a database and subsequently retrieving them for use? Or does the instruction to "Save the Long type as-is in your application" signify a dead end in this scenario? It seems implausible that the developers behind this service bus package would offer no flexibility in saving such IDs.

Your input and suggestions are highly appreciated.

Thank you!

Answer №1

To put it briefly:

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

For more insight, you may want to check out this related post Node js Mongodb Query NumberLong

Answer №2

The Mongo Long data type is not directly supported by @azure/service-bus. However, upon examining the plugin's source code, I discovered a helpful comment within the definition of the Long type:

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

By utilizing this alternative compatible type and integrating the mongoose-long npm package, which extends support for the Long data type that is harmonious with Long from 'long', I was able to successfully store data in mongo.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting in MongoDB by words can help organize the data in a more

Having the following data. { "summary": "testing api1", "UpdatedDate": { "$date": "2018-12-30T00:00:00.000Z" }, "status": "draft" }, { "summary": "testing api2", "UpdatedDate": { "$date": "2018-12-30T00:00:00.000Z" ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

Objects in the array are failing to sort in the expected sequence

I am facing an issue with sorting an array of objects by a date property using the lodash function orderBy. I have tried to sort it in both ascending and descending order. var searchObj = [{id: 1, postDate: '2/24/2016 5:08 PM'}, ...

Updating the parent navigation bar after a successful login in a child component in Angular4

In my Angular4 project, I have set up a login page. Within the parent app.component file, I have included a navigation bar with login and signup buttons. Upon successful login, the login and signup buttons should be hidden, and the username should appear i ...

Can an excessive amount of classes cause my Angular application to run sluggishly?

Within my Angular 7 application, I have generated approximately 200 to 300 classes for model types (e.g. component.model.ts) solely for type checking purposes. I have not instantiated any objects from these classes. As I navigate through the application, ...

Guide to executing API PATCH request on the server for a system that approves outings?

I have developed a system for approving outings using the MERN Stack. I wrote code to change the leave status to "Approved", but the changes are not saved when I refresh the page. The PATCH request works fine through Postman. Mongoose Schema Snippet for l ...

Error exporting variables in NodeJS causing confusion

I'm currently in the process of transitioning a Meteor application from TypeScript to Javascript. While working on the server side, I've encountered some issues with the import/export code that functioned smoothly in TypeScript but now seems to b ...

The compatibility issue between Tailwind CSS and Material UI has been identified in the latest version of Next, version 14.0

Currently, I am working with Next 14.0.2 alongside Material UI and Tailwind CSS for my Frontend development tasks. However, I've run into some challenges regarding styling components. One specific issue I faced was when setting a button to navigate to ...

The Node.js timestamp is later than the current date of the client

When storing data in MongoDB with the recording date, I utilize new Date() in Node.js and return that date with an AJAX response. To calculate the elapsed time from when the data was stored in MongoDB, I create a new date on the client-side. Then, I determ ...

What is the proper way to utilize RxJS to append a new property to every object within an array that is returned as an Observable?

I'm not very familiar with RxJS and I have a question. In an Angular service class, there is a method that retrieves data from Firebase Firestore database: async getAllEmployees() { return <Observable<User[]>> this.firestore.collectio ...

When `strictNullChecks` is turned on, how does the `void` type differ from the `undefined` literal type?

When strictNullChecks is turned on: (u: undefined, v: void, n: null) => { v = u; u = v; // type error: Type 'void' is not assignable to type 'undefined' v = n; // type error: Type 'null' is not assignable to type &ap ...

Blazing Paths with an Isomorphic Application Using Inferno and TypeScript

I am currently working on building an isomorphic application using Express and Inferno. Strangely, I have not come across any similar projects online. In my attempt to create one myself by following a guide on Razzle, specifically related to Inferno, I enc ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

Angular problem arises when attempting to map an array and selectively push objects into another array based on a specific condition

Setting up a cashier screen and needing an addToCart function seems pretty simple, right? However, I am encountering a strange logical error. When I click on an item to add it to the cart, my function checks if the item already exists in the array. If it d ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

Generate a data type automatically based on an Array

Imagine having an imaginary api that provides color values based on user selections. Consider the following arrays with string values: const Colors1 = ['red', 'blue', 'purple']; const Colors2 = ['blue', 'white& ...

Determining the parent type in Typescript by inferring it from a nested member

Typescript has the ability to infer the type of a value based on queries made within if statements. For instance, the type of one member of an object can be deduced based on another: type ChildType = 'a' | 'b'; type Child<T extends ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

The automatic filtering feature does not kick in when the sorting is changed

I've been working on an app that features a video database, allowing users to filter videos by category and sort them by rating. https://i.sstatic.net/cESZT.png Currently, the filtering system works fine once the options are changed. However, there ...

What causes a folder to disappear after rerunning in nest.js?

When working on my project using nest.js in MacOS Sonoma, I encountered a problem where the image folder src/products/images gets deleted after every project rerun (npm start). The images are saved like this: for (const image of images) { const fileName ...