Typescript gives me an error. The error is due to the fact that mongoose expects that the promise of a search will resolve with a mongoose document (in this case the document of the user) or "null". But I want to access all the user's methods, so I have to specify that that function will take the user's model as an argument. But this thing causes me the following error:
Argument of type '(user: UserModel) => Response' is not assignable to parameter of type '(res: Document | null) => void | Response | PromiseLike'.
This is the code:
import express, { Request, Response } from "express";
import User, { UserModel } from "../../models/User";
// router
const router = express.Router();
// @route GET api/user/username/:username
// @access Public
router.get("/username/:username", (req: Request, res: Response) => {
User.findOne({ username: req.params.username })
.then((user: UserModel | null) => res.json(user))
.catch(err => res.json(err));
});
export default router;
This is the user's model:
import mongoose, { Schema, model } from "mongoose";
export type UserModel = mongoose.Document & {
name: string;
username: string;
email: string;
password: string;
avatar: string;
created_at: Date;
};
export const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
unique: true
},
password: {
type: String,
required: true
},
avatar: {
type: String
},
created_at: {
type: Date,
default: Date.now
}
});
export default model("User", UserSchema);