Question:
I’m implementing a custom Mongoose schema type called Password for handling password hashing using bcrypt. However, I’m encountering a TypeScript error specifically related to the return type of the cast function.
Error Message:
{
username: 'admin',
password: Promise { <pending> },
_id: new ObjectId('668ac8e979f8098acd8399fb'),
__v: 0
}
Environment:
- Operating System: Debian 64 bit
- Node.js: 14.17.0
- TypeScript: 4.5.4
- Mongoose: 6.1.1
Code Snippets:
Here’s how I’ve defined the Password schema type class:
import bcrypt from "bcrypt";
import mongoose, { SchemaTypeOptions } from "mongoose";
// Define the number of salt rounds for bcrypt hashing
const SALT_ROUNDS = 10;
export default class Password extends mongoose.SchemaType {
constructor(
key: string,
options: SchemaTypeOptions<string>
) {
// Call the parent constructor with the key, options, and type name
super(key, options, "Password");
};
async cast(value: string) {
const hash = await bcrypt.hash(value, SALT_ROUNDS);
return hash;
};
async compare(password: string, hash: string) {
return await bcrypt.compare(password, hash);
};
};
Expected Output:
I expect the cast function in the Password schema type to correctly return a hashed password (string) after hashing the provided plaintext password (value) using bcrypt. However, TypeScript is throwing an error indicating that the return type of Promise is not assignable to type string.
Additional Information:
- Reviewed bcrypt’s documentation on asynchronous hashing and TypeScript typings.
- Explored relevant Stack Overflow questions and GitHub issues but couldn’t find a solution specific to this TypeScript error.
Any guidance or suggestions on resolving this TypeScript error in the cast function would be greatly appreciated. Thank you for your assistance!