aravindnc / mongoose-paginate-v2

A custom pagination library for Mongoose with customizable labels.

Home Page:https://www.npmjs.com/package/mongoose-paginate-v2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

NodeJS throws error on version 17.3.0 & 16.3.1

arkanos opened this issue · comments

Describe the bug
Using NestJS and after adding mongoose-paginate-v2 to the schemas, when using any endpoint that uses pagination, NodeJS throws the following error:

Error: This is caused by either a bug in Node.js or incorrect usage of Node.js internals.
Please open an issue with this stack trace at https://github.com/nodejs/node/issues

    at new NodeError (node:internal/errors:371:5)
    at assert (node:internal/assert:14:11)
    at ServerResponse.detachSocket (node:_http_server:247:3)
    at resOnFinish (node:_http_server:817:7)
    at ServerResponse.emit (node:events:390:28)
    at onFinish (node:_http_outgoing:830:10)
    at callback (node:internal/streams/writable:553:21)
    at afterWrite (node:internal/streams/writable:498:5)
    at afterWriteTick (node:internal/streams/writable:485:10)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)

Any other endpoint that makes use of the same model/schema but without pagination, works without any issue.

This is an example of how I define the schemas:

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document } from "mongoose";
import { Roles } from "./roles.enum";
import * as mongoosePaginate from 'mongoose-paginate-v2';
import { Types } from "mongoose";

export type RoleDocument = Role & Document;

@Schema({ timestamps: true })
export class Role {

    _id: Types.ObjectId;

    @Prop({ type: String, required: true, enum: Roles, unique: true })
    name: string;

    @Prop()
    createdAt?: Date

    @Prop()
    updatedAt?: Date
}

export const RoleSchema = SchemaFactory.createForClass(Role);

RoleSchema.plugin(mongoosePaginate);

And this is how I use the plugin in the service:

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { PaginateModel, PaginateResult } from 'mongoose';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { Role, RoleDocument } from './roles.schema';

@Injectable()
export class RolesService {

    constructor(
        @InjectModel(Role.name) private roleModel: PaginateModel<RoleDocument>,
    ) { }

    async create(role: CreateRoleDto): Promise<Role> {
        const newRole = new this.roleModel(role);
        return newRole.save();
    }

    async findRoles({ name, page = 1, limit = 10 }): Promise<PaginateResult<RoleDocument>> {
        let query = {};
        if (name) query = { name: { $regex: name, $options: 'i' } };
        const options = {
            populate: [],
            page: Number(page),
            limit: Number(limit),
            lean: true,
            leanWithId: false,
            customLabels: {
                docs: 'roles',
                totalDocs: 'total'
            }
        };
        return await this.roleModel.paginate(query, options);
    }

    async getById(id): Promise<Role> {
        return await this.roleModel.findById(id).select({}).lean();
    }

    async getByNames(roles: string[]): Promise<Role[]> {
        return await this.roleModel.find({ name: { $in: roles } }).lean();
    }

    async update(id, role: UpdateRoleDto): Promise<Role> {
        const updatedRole = await this.roleModel.findByIdAndUpdate(id, { ...role }, { new: true })
        return updatedRole
    }

    async delete(id): Promise<any> {
        return await this.roleModel.findByIdAndRemove(id);
    }

}

Not sure if this is related with the plugin itself, NodeJS in mac or the combination of NestJS + the plugin. Further investigation is on course.

Even if error is thrown, endpoint returns the data properly structured as defined in plugin options.

To Reproduce
Steps to reproduce the behavior:

  1. Generate a NestJS module
  2. Setup any controller & service that uses a Mongoose schema/model with plugin for pagination
  3. Make the request to such endpoint
  4. Error is displayed in console

Expected behavior
No error should be thrown.

Desktop (please complete the following information):

  • OS: macOS Monterey 12.0.1
  • NodeJS 17.3.0 & 16.3.1

Tried to build the project inside a Docker image using Node Alpine image for 16.13.1 just to discard it was an OS issue but error pops up as well.

After several hours of investigation, I have found that this is not caused by the plugin but is something related with NestJS. I'm opening the issue on their repo. Sorry for any inconvenience.