Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserModel is not assignable to parameter of type Document | nulll [mongoose with Typescript]

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);
like image 941
Niccolò Caselli Avatar asked Jan 27 '23 05:01

Niccolò Caselli


1 Answers

The model function accepts a type argument for the document type of the collection. (It's trusting you; it doesn't have any way to verify that the type is correct.) Replace:

export default model("User", UserSchema);

with:

export default model<UserModel>("User", UserSchema);

Then all queries on this collection will produce UserModel objects.

like image 121
Matt McCutchen Avatar answered Jan 29 '23 20:01

Matt McCutchen