node.jstypescriptmongoose

How to define what type of value .toJSON() returns when called on a Mongoose Document?


I am trying to define a toJSON function in my schema so that it will remove __v and replace _id as id and remove pwd from the document as well when .toJSON is called.

import { model, Schema } from "mongoose";

interface testType {
    name: string;
    pwd: string;
}

interface testWithId {
    id: string;
    name: string;
}

const testSchema = new Schema<testType>(
    {
        name: String,
        pwd: String,
    },
    {
        toJSON: {
            virtuals: true,
            transform: function (doc, ret): testWithId {
                return {
                    id: doc._id.toString(),
                    name: doc.name,
                };
            },
        },
    }
);
const Test = model<testType>("meow", testSchema);

async function addData(data: testType): Promise<testWithId> {
    let returnedJson = (await new Test(data).save()).toJSON();
    return returnedJson;
}

I tried doing this but when I run the code I get this error:

Property 'id' is missing in type 'FlattenMaps<testType & { _id: ObjectId; } & { __v: number; }>' but required in type 'testWithId'.

I looked in the Mongoose documentation but there is nothing mentioned about how to use type toJSON properly in the TypeScript section. Is there a way to do this or should I not be doing this and just convert the data to proper type in the addData function?


Solution

  • Force return type of .toJson() by adding generic parameter for this function:

    const returnedJson = (await new Test(data).save()).toJSON<testWithId>();
    //    ^? testWithId