我是TypeScript的新手,在我的express和MongoDB应用程序上遇到了这个错误。
这是我的User.ts模型。
import mongoose from "mongoose";
interface IUser {
username: string;
password: string;
email: string;
isAdmin: boolean;
}
const userSchema = new mongoose.Schema<IUser>(
{
username: {
type: String,
required: true,
unique: true,
minlength: 3
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true
},
isAdmin: {
type: Boolean,
default: false,
}
},
{
timestamps: true,
}
)
export const UserModel = mongoose.model<IUser>("User", userSchema);
这是我的路线,当我试图访问密码时,我会得到错误。
router.get( "/:id", verifyToken, async (req: any, res: any) => {
const user = await User.findById(req.params.id);
if (!user) {
res.status(404).json({ message: "User not found" });
}
const {password, ...other} = user;
res.status(200).json(other);
}
)
完整错误:
TSError: ⨯ Unable to compile TypeScript:
routes/user.ts:28:12 - error TS2339: Property 'password' does not exist on type '(Document<unknown, any, IUser> & IUser & { _id: ObjectId; }) | null'.
28 const {password, ...other} = user;
我正在做他们docs中所说的事情,所以我有点不知所措。
1条答案
按热度按时间nue99wik1#
我必须定义变量user。