gpt4 book ai didi

node.js - TypeScript 错误 : Object literal may only specify known properties, 和 '...' 在类型 'DeepPartial' 中不存在

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:25 26 4
gpt4 key购买 nike

我尝试使用 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);

关于node.js - TypeScript 错误 : Object literal may only specify known properties, 和 '...' 在类型 'DeepPartial<Document>' 中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com