Correctly inputting MongoDB-specific collection methods which are currently defaulting to "any"

I'm facing an issue with typing Mongo collection method responses in my app. Specifically, I am having trouble finding a way to type the response of the deleteMany method. The documented response should look like this:

{ "acknowledged" : true, "deletedCount" : X }

Is there a predefined type for this in Mongo? Or do I need to manually define it myself?

This problem has become apparent during an upgrade from an older version of Mongo to v6, as the response no longer includes the ok property. It would be helpful to have a type that could catch such changes and show TypeScript errors.

Currently, the code snippet looks like this:

const res = await this.deleteMany(query)  // res is currently an any type


if (res.deletedCount > 10) {
  // do something 
} else {
 // do something else
}

The main issue here is that res is typed as any. I am wondering if I need to create a custom type or if there is a pre-existing one that can be imported to handle potential changes in future versions.

Any insights would be appreciated. Thanks!

Answer №2

If you are using the latest mongodb Node.js driver version (5.2.0 at this moment), you should have automatic TypeScript definitions included.

When properly configured, your res variable will be correctly typed as a DeleteResult, and any missing properties like ok will be flagged:

import { MongoClient } from 'mongodb'; // Version 5.2.0

interface Pet {
    name: string;
    kind: 'dog' | 'cat' | 'fish';
}

const client = new MongoClient('mongodb://localhost:27017');
const pets = client.db().collection<Pet>('pets');

const res = await pets.deleteMany();
//    ^? DeleteResult

if (res.deletedCount > 10) { // Okay
    // do something 
} else {
    // do something else
}

res.ok; // Error: Property 'ok' does not exist on type 'DeleteResult'.
//  ~~

Playground Link

Ensure that your this context is correctly typed as a Mongo Collection from the beginning.

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

Issue with nestjs build due to ts-loader module in dev-dependency

I've encountered a Module Error with ts-loader during a docker build ERROR [6/6] RUN nest build 3.9s ------ > [6/6] RUN ...

Unable to mock ESM with unstable_mockModule

In my project, I am utilizing ESM. The transpiled .ts files are converted into .js and stored in the 'dist' directory. Here is an example of how my directory structure looks: dist/ ├─ src/ │ ├─ store/ │ │ ├─ index.js │ ├ ...

The HTML table is displaying with an offset, which is probably caused by the *ngFor directive

I'm having trouble aligning the HTML table properly, as it seems to be misaligned. The issue I am facing is related to the inner loop (modification) which is a list inside of Revision (basically, Revision 'has a' modification list). Althoug ...

Strategies for successfully passing and showcasing the result of a calculation on a fresh view or component within Angular

I have developed a basic calculator application with two main components: Calculator and Result. The Angular router is used to navigate between these components. Now, I am looking for a way to dynamically display the calculation result from the Calculator ...

Why is the removal of this type assertion in TypeScript causing an issue?

Why is TypeScript refusing to compile this code snippet? interface TaggedProduct { tag: string; } interface Product { tag?: string; } const tagProduct = (product: Product): TaggedProduct => { const tag: string = "anything"; pro ...

Loading screen displayed while transitioning between routes within Angular

I have been struggling to implement a loading spinner in my project. How can I display a loading screen when changing routes in Angular? Here is the HTML code snippet: <div *ngIf="showLoadingIndicator" class="spinner"></div> ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

Mocking the MongoDB repository's `save` method produces the expected result, while all other mock methods will simply return null

I'm currently in the process of testing a service that relies on a MongoDB ReactiveMongoRepository repo as a dependency. Utilizing @MockBean to inject a mock repository, I've encountered an issue where only one out of the four defined when().then ...

a callback may seem like it's not a function, but in reality, it is

This question might seem simple, but I'm struggling to grasp the concept of callbacks, especially in NodeJS. My issue arises when trying to retrieve data from MySQL, something that is usually straightforward in most programming languages: In my rout ...

Perform an action after the Ngx Bootstrap modal has been hidden

My modal features a login button: <button type="button" (click)="save()" class="btn btn-primary"> login </button> Upon clicking the button, my desired outcome is to: first hide the modal, and second navigate to another route. However, ...

Guide to crafting a personalized parameter decorator for extracting the user from a request

Within my express.js application, I have set up an endpoint where I extract the user from the request as shown below: @Put('/:_id') async update (@Request() req: express.Request) { // @ts-ignore const user = req.user; .... } I am intereste ...

Having trouble using PHP's array_reduce() function? Seeing an error message that says "invalid function name"?

Encountered an issue while using the array_reduce() function. I believe the syntax is correct for this operation. The purpose of this function is to calculate the sum of numbers in an array. function sum($el1, $el2){ if(!isset($return_sum)) $r ...

It is possible that req.user may be undefined, especially when using express and passport.js

I am facing an issue with my Node.js TypeScript authentication system that utilizes passport. The problem arises when I attempt to access req.user in a specific route, resulting in the error message: Object is possibly 'undefined'. This behavio ...

Error: The function visitor.visitUnaryOperatorExpr is not defined as a function

I recently started developing an Angular app with a purchased template and collaborating with another developer. Initially, I was able to successfully build the project for production using ng build --prod. However, when trying to build it again yesterday, ...

An unusual problem encountered while working with NextJS and NextAuth

In my NextJS authentication setup, I am using a custom token provider/service as outlined in this guide. The code structure is as follows: async function refreshAccessToken(authToken: AuthToken) { try { const tokenResponse = await AuthApi.refre ...

Experiencing Timeout Issue When Attempting to Submit Data

Hey there, I'm currently working on setting up a file upload feature using node.js and mongodb. However, I've encountered a timeout error when trying to post the data. Here is the code snippet I'm using: app.post('/photos/new', fu ...

Using React with Typescript: Passing Props and Defining Data Types

As a relatively new TypeScript enthusiast, I find myself facing some challenges. Specifically, I am struggling with errors in my code and uncertain about how to properly pass props and select the correct type. Any guidance on this matter would be greatly a ...

Utilizing a personalized (branched) @types package

I have taken the @types/stripe package from the DefinitelyTyped repository on GitHub and created my own version in my personal GitHub repo / npm module. I understand that this custom type module may not work automatically. I attempted to integrate it by ...

Guide to importing a function from a Javascript module without declaration

Currently, I am utilizing a third-party Javascript library that includes Typescript type declarations in the form of .d.ts files. Unfortunately, as is often the case, these type declarations are inaccurate. Specifically, they lack a crucial function which ...

Sorting through an array of objects using a filter method

While following a tutorial, I decided to make some changes to the TypeScript for learning purposes. However, I encountered a problem when trying to create a filter function from a React context script. I have successfully implemented a function called get ...