我正在尝试使用TypeScript在NodeJS中创建一个简单的控制器API,但是当我为模型分配值时遇到错误ts(2345)
。
这是我的用户模型:
import mongoose, {Schema} from 'mongoose'
const userSchema: Schema = new Schema({
_id: Schema.Types.ObjectId,
login: {
type: String,
unique: true,
required: true
},
email: {
type: String,
unique: true,
match: (value: string) => /\S+@\S+\.\S+/.test(value),
required: true
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
})
export default mongoose.model('User', userSchema)
和控制器:
import User from '../models/User'
import {Request, Response} from 'express'
export class UserController {
public addNewUser (req: Request, res: Response) {
const {login, email, password} = req.body
// some code
const newUser = new User({
// ts error:
// Argument of type '{ login: any; email: any;
// password: any; date: number; }' is not assignable
// to parameter of type 'DeepPartial<Document>'.
// Object literal may only specify known properties,
// and 'login' does not exist in type
// 'DeepPartial<Document>'.ts(2345)
login,
email,
password,
date: Date.now()
})
}
}
我找到了解决此错误的方法:
const newUser = new User({
login,
email,
password,
createdAt: Date.now(),
...req.body
})
但是我不确定这是否是一个好方法,但仍然不知道为什么我总是会遇到此错误。有帮助吗?
答案 0 :(得分:0)
问题在于req.body没有定义{login,email,password},并且使它们成为“ any”。 TS不喜欢它,如果您在需要特定类型的情况下尝试向对象添加“ any”。您可以将req强制转换为包含主体对象的类型,该主体对象包含登录名,电子邮件和密码。像这样:public addNewUser (req: UserRequest, res: Response) {...}
和interface UserRequest {body: {login: string; email: string; password: string}}
希望这会有所帮助。编码愉快
答案 1 :(得分:0)
尝试这样声明模型:
import mongoose, { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
firstName: string;
lastName: string;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true }
});
// Export the model and return your IUser interface
export default mongoose.model<IUser>('User', UserSchema);