Is it possible to define the return type of the toObject
method in Mongoose?
When working with generics, you can set properties of a Document
object returned from a Mongoose query. However, accessing getters and setters on these objects triggers various validation codes, which may not be desired in certain scenarios.
The Document
objects have a toObject
method that returns an anonymous object with the type any
. I want to specify the type of these objects in the Schema
or Model
definition so that I don't have to use type assertion every time I execute a query.
My current code snippet looks like this:
import mongoose, { Schema, Document } from 'mongoose'
interface User {
username: string,
email: string,
password: string,
}
const UserSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
})
const UserModel = mongoose.model<User & Document>('User', UserSchema)
export { User, UserModel }
Using the above code, I can perform a query using the following snippet:
const userDocument = await UserModel.findById(id)
const userObj = userDocument && userDocument.toObject()
While userDocument
is of type User extends Document
, userObj
has the type any
. My goal is to change its type to User
.