我尝试使用 TypeScript 在 NodeJS 中创建一个简单的 Controller 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)
和 Controller :
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
})
但我不确定这是一个好方法,并且仍然不知道为什么我会收到此 ts 错误。有什么帮助吗?
尝试像这样声明你的模型:
import * as 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);
我是一名优秀的程序员,十分优秀!