我正在尝试在渲染上部署 MERN 应用程序。 构建出现此错误。
../backend/src/models/hotel.ts(1,22): error TS2307: Cannot find module 'mongoose' or its corresponding type declarations.
../backend/src/models/user.ts(1,22): error TS2307: Cannot find module 'mongoose' or its corresponding type declarations.
../backend/src/models/user.ts(2,20): error TS2307: Cannot find module 'bcryptjs' or its corresponding type declarations.
../backend/src/models/user.ts(22,8): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
../backend/src/models/user.ts(23,9): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
../backend/src/models/user.ts(23,43): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
user.ts 文件是:
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
export type UserType = {
_id: string;
email: string;
password: string;
firstName: string;
lastName: string;
};
const userSchema = new mongoose.Schema({
email:{type:String,required:true,unique:true},
password:{type:String,required:true},
firstName:{type:String,required:true},
lastName:{type:String,required:true}
});
//function to be executed before saving the user to the database
//this is actually a middleware
userSchema.pre("save", async function(next: mongoose.CallbackWithoutResultAndOptionalError){
if(this.isModified("password")){
this.password = await bcrypt.hash(this.password,10);
}
next();
});
const User = mongoose.model<UserType>("User",userSchema);
export default User;
我通过此命令安装了 mongoose 和 bycryptjs 类型:
npm install --save-dev @types/mongoose @types/bcryptjs
我的tsconfig.json文件包括:
{
"compilerOptions": {
"types": ["node"]
}
}
当我将鼠标悬停在此处时,我的 VS Code 会显示以下内容
this: mongoose.Document<unknown, {}, mongoose.FlatRecord<{
firstName: string;
lastName: string;
email: string;
password: string;
}>> & mongoose.FlatRecord<{
firstName: string;
lastName: string;
email: string;
password: string;
}> & {
...;
}
这些是我的版本:
"@types/mongodb": "^3.6.8",
"@types/mongoose": "^5.11.97",
"@types/bcryptjs": "^2.4.6",
"bcryptjs": "^2.4.3",
"mongodb": "^6.3.0",
"mongoose": "^6.0.12",
这是我的渲染构建命令。
cd frontend && npm install && npm run build && cd ../backend && npm run build
但我仍然收到此错误,我不知道该怎么办。