Home > Software design >  Return mongoose document TypeScript
Return mongoose document TypeScript

Time:11-21

I'm Trying to return a mongoose document, but then i get this error:

Type '(IPersonDocument & { _id: ObjectId; })[]' is missing the following properties from type 'IPersonDocument': firstName, lastName, groups, $assertPopulated, and 52 more.ts(2740)

IPersonDocument is extends IPerson and Mongoose.Document

this is my code:

repo.ts

export async function findByName(name: String): Promise<IPersonDocument>{
    return await PersonsModel.find({ firstName: name }) //problem here
}

type.ts

import { Document, Model } from "mongoose";

export interface IPerson {
    firstName: string;
    lastName: string;
    age?: number;
    email?: string,
    groups: [String],
    dateOfEntry?: Date;
}

export interface IPersonDocument extends IPerson, Document { }

export interface IPersonModel extends Model<IPersonDocument> { }

moduel.ts

import { model } from "mongoose";
import { IPersonDocument } from "../../../type/person.types";
import PersonsSchema from "./person.schema";

export const PersonsModel = model<IPersonDocument>("persons", PersonsSchema)

CodePudding user response:

add the lean()

return await PersonsModel.find({ firstName: name }).lean();

its coavert the DOC object to js object.

  • Related