Я пытаюсь создать простой API контроллера в NodeJS с помощью TypeScript, но получаю сообщение об ошибке 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
})
Но я не уверен, что это хороший подход, и до сих пор не знаю, почему я вообще получаю эту ошибку ts. Любая помощь?





Проблема в том, что req.body не определяет {логин, адрес электронной почты, пароль} и делает их "любыми". ТС не любит, если к объекту пытаются добавить "любой", если нужен конкретный тип. Вы можете привести req к типу, который содержит объект body, который содержит логин, адрес электронной почты и пароль. Как это:
public addNewUser (req: UserRequest, res: Response) {...}
и
interface UserRequest {body: {login: string; email: string; password: string}}
Попробуйте объявить свою модель следующим образом:
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);
Модуль '"mongoose"' не имеет экспорта по умолчанию.
Вы должны импортировать его следующим образом: import * as mongoose from 'mongoose';
Спасибо за ответ. К сожалению, ошибка все еще возникает:
Argument of type '{ login: string; email: string; password: string; date: number; }' is not assignable to parameter of type 'DeepPartial<Document>'. (...)