Type 'document' Is Missing The Following Properties From Type
Solution 1:
I do not know where the problem exactly but this is how I create mongoose schema using TypeScript and it works for me.
import * as mongoose from'mongoose';
interfaceSavedUserDocumentextends mongoose.Document {
firstName: string;
lastName: string;
email: string;
}
constSavedUserSchema = new mongoose.Schema({...});
exportconstSavedUser = mongoose.model<SavedUserDocument>('saveduser', SavedUserSchema);
Hope it works for you as well.
Solution 2:
Mongoose returns more on .save()
then you are currently specifying with the SavedUser interface.
The easiest way of getting all the types from Mongoose, is by using the exported Document
and extending your interface.
import { Document } from'mongoose';
exportinterfaceSavedUserextendsDocument {
email: string;
firstName: string;
lastName: string;
}
Solution 3:
Thanks for answering I solved it! I mixed dijkstra and phw's answer and came up with this:
In my User Model
//user.ts
import { Schema, model, Document } from'mongoose'constuserSchema=newSchema({firstName: {
type:String,
required:true,
min:2,
max:255
},lastName: {
type:String,
required:true,
min:2,
max:255
},email: {
type:String,
required:true,
unique:true,
min:6,
max:255
}
})exportinterfaceSavedUserDocumentextendsDocument {
firstName:string;lastName:string;
}
exportconstuserSchemaModel=model<SavedUserDocument>('User',userSchema)
now on my User Controller:
//user.ts
import { userSchemaModel, SavedUserDocument } from'../../models/user/user'
...
publicasyncsignUp(req: Request, res: Response): Promise<void | Response> {
const user = newuserSchemaModel({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
})
try {
const { firstName, lastName }: SavedUserDocument = await user.save()
return res.status(200).send({
firstName,
lastName,
message: 'User created'
})
} catch (err) {
return res.status(400).send(err)
}
}
...
I do have a question;
If I removed the <SavedUserDocument>
in model<SavedUserDocument>('User', userSchema)
I would still receive the error, can i have a good explanation of that? i'm still relatively new with Typescript and would be great to get an explanation, Thank you very much!
Post a Comment for "Type 'document' Is Missing The Following Properties From Type"