"Error encountered: 'Callable function cannot be invoked on Mongoose model

In my Nest JS service, the code structure is as follows:

import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { Collection } from './interfaces/collection.interface';
import { CollectionDto } from './dto/collection.dto';
import { COLLECTION } from '../constants';

@Injectable()
export class CollectionsService {
  constructor(
    @InjectModel(COLLECTION) private readonly collectionModel: Model<Collection>
  ) {}

  async getAllCollections(): Promise<Collection[]> {
    const collections = await this.collectionModel.find().exec();
    return collections;
  }

  async addCollection(collectionDto: CollectionDto): Promise<Collection> {
    const newCollection = await this.collectionModel(collectionDto);
    return newCollection.save();
  }
}

Although the code works fine, I encountered a tslint warning ts(2348). Can anyone suggest an alternative approach to resolve this issue without using the // @ts-ignore rule?

https://i.stack.imgur.com/5ZLQY.png

Answer №1

If you're facing this issue, give the new keyword a try like I did. Here's my solution for your reference.

const newObj = await new this.objectModel(objectDto);

Answer №2

To implement this, consider using the code snippet new newCollection.save();. Keep in mind that the schema functions as a constructor.

This technique has been successful in Node.js and should be applicable in React as long as both platforms are utilizing Mongoose.

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

Exploring the inner workings of MongoDB queries within the context of Node.js

I have a simple search query in Node.js Express.js MongoDB with Mongoose: await Model.find({}).limit(10); My question is about the process flow. Do architects first retrieve all data from Models and then limit to 10, or do they select 10 items directly fr ...

The combination of React Vite and SockJS Client has encountered a failure in all transport

My current project is utilizing react + vite without any proxy configuration. I am attempting to use webstomp-client and sockjs to establish a connection with a websocket server that is supported by Springboot using SockJS. The backend Springboot server w ...

incongruity discovered during string conversion in HmacSHA256 within Ionic framework

I am facing an issue while trying to create a token in IONIC using the CryptoJS library. The signature generated by the method is different from what I expect. The expected signature is lLJuDJVb4DThZq/yP4fgYOk/14d3piOvlSuWEI/E7po= but the method provides m ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

Understanding the fundamentals of TypeScript annotation and node package management

As a newcomer to Typescript, I have grasped the basics but find myself becoming a bit bewildered when it comes to best practices for handling node packages, annotations, and defining types within those packages in my projects. Do I really need to annotate ...

Guide for adding an OnClick event to a MatTable row:

I am looking to add functionality for clicking on a specific row to view details of that user. For instance, when I click on the row for "user1", I want to be able to see all the information related to "user1". Here is the HTML code snippet: <table ma ...

Using Mongoose with Next.js to implement CRUD operations

I have been successful in implementing POST and GET methods in my Next.js app using mongoose, but I am facing challenges with the delete operation. This is an example of my POST method located in the API folder: export default async function addUser(req, ...

Utilizing Conditional CSS Classes in React Material-UI (MUI) 5

I am in the process of migrating from React material-ui 4 to MUI 5. How can I implement this particular design pattern using the new styled API (or any other suitable method)? My project is written in Typescript. const useStyles = makeStyles(theme => ...

Can you explain the significance of <any> when used before a Typescript class constructor parameter?

Currently, I am immersing myself in the Angular - Testing documentation. While going through the section on testing asynchronous services (specifically HTTP services), I came across a class constructor containing an <any> right before the passed argu ...

The Angular Material Autocomplete component fails to show items upon upgrading the angular/material package to the newest version

Issue with Angular Material Autocomplete component not displaying items after updating angular/material package to the latest version. The autocomplete was functioning correctly with "@angular/material": "^2.0.0-beta.10" but encountered issues when update ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

What is the process for linking a form submission in NextJS to MongoDB?

I'm currently diving into NextJS and struggling to connect my form with the database. Which hooks should I be using alongside Next for this task? I've been adding data through Postman, but I can't seem to establish the connection with the f ...

Tips for ensuring a function in Angular is only executed after the final keystroke

I'm faced with the following input: <input type="text" placeholder="Search for new results" (input)="constructNewGrid($event)" (keydown.backslash)="constructNewGrid($event)"> and this function: construct ...

Ways to transmit data multiple times within a single request

I'm currently developing an app using Nodejs and express, where orders can be placed for specific products. In this application, when an order is received, it is saved in the database and a PDF receipt is generated immediately. However, since generati ...

Error: Unable to verify the user's identity. Mongoose

I have a node and MongoDB Docker application running on my local machine, but when I attempt to connect to the database using Mongoose, it gives me the following error: MongoError: Authentication failed. at MessageStream.messageHandler (D:\Node&bs ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

invoking a method within an express route to retrieve and utilize middleware functions

For my project, I am working on a custom function to handle API request validation. Here is how it looks: export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void { return function ...

How to turn off automatic password suggestions in Chrome and Firefox

Currently, I have integrated a 'change password' feature which includes fields for 'old password', 'new password', and 'retype password'. However, the autocomplete feature is suggesting passwords from other user acco ...

Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I&ap ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...