So I have this mongoose model as below:
const userSchema: mongoose.Schema = new mongoose.Schema(
{
_id: String,
email: {
type: String,
required: true,
},
firstName: String,
lastName: String,
phoneNumber: String,
cmt: {
type: String,
ref: 'Cmt',
},
},
);
As you can see cmt field is pointing to another model called Cmt
whose details I'll be getting used populate
now on another instance i need to pass in the cmt id for linking it with the userSchema
but at that time i'll get a typescript error of "Type 'string' is not assignable to type 'ICmt'."
ICmt
being the interface definition of Cmt.
The userschema interface is given below.
export interface IUser {
_id: string;
email: string;
firstName: string;
lastName: string;
phoneNumber: string;
cmt: ICmt;
createdAt?: Date;
updatedAt?: Date;
}
How can I fix this error without messing both populate query and create query?
This was an easy solution, wrong on my end.
You could use an |
(or)
statement on the interface, that will solve the problem for the tslint errors that may occur
So my user interface will become
export interface IUser {
_id: string;
email: string;
firstName: string;
lastName: string;
phoneNumber: string;
cmt: ICmt | string;
createdAt?: Date;
updatedAt?: Date;
}
So there won't be any more tslint errors or tsignore that I need to worry about
The following will work, but will require type checking for either case.
export interface User { // Issue when using I in declarations v.6++
cmt: Cmt | mongoose.Types.ObjectID;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.