Search code examples
node.jstypescriptmongodbmongoosenestjs

mongoose model.save() return TypeError: callback is not a function


In my nestjs project I'm using mongoose and getting TypeError: callback is not a function while I'm trying to model.save().

"@nestjs/common": "^8.0.0",
"@nestjs/config": "^1.2.0",
"@nestjs/core": "^8.0.0",
"@nestjs/mongoose": "^9.0.2",
"mongoose": "^6.2.6",

In my tags.service.ts for storing data I have this function:

async create(createTagDto: CreateTagDto): Promise<Tag> {
   return await new this.tagModel(createTagDto).save();
}

According to Mongoose documentation by saving a document this should return a Promise.

In my tags.controller.ts I define endpoint by calling service function above by:

@Post()
async create(@Body() createTagDto: CreateTagDto) {
    return await this.tagsService.create(createTagDto);
}

Trying to post data to the endpoint, the new document is created in the database but the server return Internal server error with status code 500. The only description in the console is above mentioned TypeError: callback is not a function somewhere in node_modules/mongoose/lib/statemachine.js:137:14.

Does anyone experienced such an issue?


Solution

  • Above mentioned error was caused by using nestjs global interceptor app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector))) in the main.ts bootstrap function. However the build-in ClassSerializerInterceptor cannot figure out a returned mongo Document, a custom interceptor have to be used to properly serialize returned data.