Intento crear el método hashPassword para el esquema de usuario.
schema.method("hashPassword", function (): void { const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync(this.password, salt); this.password = hash; }); Y obtiene un error Property 'password' does not exist on type 'Document<any>'. en contraseña
Aquí está mi archivo
import mongoose, { Schema, Document } from "mongoose"; import bcrypt from "bcryptjs"; /** * This interface should be the same as JWTPayload declared in types/global.d.ts file */ export interface IUser extends Document { name: string; email: string; username: string; password: string; confirmed: boolean; hashPassword: () => void; checkPassword: (password: string) => boolean; } // User schema const schema = new Schema( { name: { type: String, required: true, }, email: { type: String, required: true, }, username: { type: String, required: true, }, password: { type: String, required: true, }, confirmed: { type: Boolean, default: false, }, }, { timestamps: true } ); schema.method("hashPassword", function (): void { const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync(this.password, salt); this.password = hash; }); // User model export const User = mongoose.model<IUser>("User", schema, "users");En el punto en el que define el método, el objeto schema no sabe que es el Schema para un IUser y no cualquier Document . Debe establecer el tipo genérico para el Schema cuando lo crea: new Schema<IUser>( ... ) .
Como lo sugirió uno de los colaboradores de mongoose, podemos usar la siguiente forma para crear métodos de instancia:
const schema = new Schema<ITestModel, Model<ITestModel, {}, InstanceMethods>> // InstanceMethods would be the interface on which we would define the methods schema.methods.methodName = function() {} const Model = model<ITestModel, Model<ITestModel, {}, InstanceMethods>>("testModel", ModelSchema) const modelInstance = new Model(); modelInstance.methodName() // worksenlace: https://github.com/Automattic/mongoose/issues/10358#issuecomment-861779692
Debe declarar una interfaz que amplíe Model así:
interface IUser {...} interface IUserInstanceCreation extends Model<IUser> {}luego declara tu esquema;
const userSchema = new Schema<IUser, IUserInstanceCreation, IUser>({...})Esto también garantizaría que el esquema siga los atributos en IUser.