[英]TypeScript Error: Object literal may only specify known properties, and '…' does not exist in type 'DeepPartial<Document>'
I'm trying to create a simple controller API in NodeJS using TypeScript, but I'm getting error ts(2345)
when I'm assigning values to the model. 我正在尝试使用TypeScript在NodeJS中创建一个简单的控制器API,但是当我为模型分配值时,我得到错误
ts(2345)
。
Here is my user model : 这是我的用户模型 :
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)
And 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()
})
}
}
I've found a solution to get off this error: 我找到了解决此错误的解决方案:
const newUser = new User({
login,
email,
password,
createdAt: Date.now(),
...req.body
})
But I'm not sure this is a good approach and still don't know why i'm getting this ts error at all. 但我不确定这是一个好方法,但仍然不知道为什么我会得到这个ts错误。 Any help?
有帮助吗?
Try to declare your model like this: 尝试声明您的模型如下:
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);
The problem is that req.body does not define {login, email, password} and that makes them "any". 问题是req.body没有定义{login,email,password},这使得它们“任何”。 TS does not like it, if you try to add "any" to an object if a specific type is needed.
如果您尝试在需要特定类型的情况下向对象添加“any”,则TS不喜欢它。 You could cast req to a type which contains a body object, which contains the login, email and password.
您可以将req强制转换为包含正文对象的类型,该对象包含登录名,电子邮件和密码。 Like this:
像这样:
public addNewUser (req: UserRequest, res: Response) {...}
and 和
interface UserRequest {body: {login: string; email: string; password: string}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.