简体   繁体   中英

Node.js Express API with TypeScript 3 Update a record

I have setup Node.js Express API with TypeScript 3 and it is working fine. I got an issue when I try to update the record.

RecordsRouter.ts

import { Router } from 'express';
import {RecordComponent} from '../../components';

const router: Router = Router();
router.get('/', RecordComponent.findAll);
router.get('/:id', RecordComponent.findOne);
router.post('/', RecordComponent.create);
router.delete('/:id', RecordComponent.remove);
router.put('/:id', RecordComponent.update);

export default router;

My RecordComponent.ts

export async function update(req: Request, res: Response, next: NextFunction): Promise <void> {
    try {
        const record: IRecord = await RecordService.put(req.body)

        res.status(201).json(record);
    } catch (error) {
        next(new HttpError(error.message.status, error.message));
    }
}

and my IRepository.ts

 export interface IRepository<T> {
    findAll(): Promise<T[]>;
    findOne(code: string): Promise<T>;
    insert(T: any): Promise<T>;
    remove(id: string): Promise<T>;
    put:(T: any)=>Promise<T>;
}

Service.ts

async put(data: IRecord): Promise { try { const validate: Joi.ValidationResult = RecordValidation.updateRecord(data);

            if(validate.error) {
                throw new Error(validate.error.message);
            }

            return await RecordModel.findOneAndUpdate(data);
        } catch (error) {
            throw new Error(error.message);
        }
    },

Did I did all correctly or something is missing because I am getting the error在此处输入图片说明

That means you didn't implement all of the interface members in RecordService . Either implement them or mark them as optional in the IRepository interface by adding a question mark before the colon:

export interface IRepository<T> {
    findAll()?: Promise<T[]>;
    findOne(code: string)?: Promise<T>;
    insert(T: any)?: Promise<T>;
    remove(id: string)?: Promise<T>;
    put(id: string)?: Promise<T>;
}

So, You should implement RecordService in next way:

const RecordService:IRepository<IRecord>={
  // ...some code for findAll, findOne ....
  remove:(id: string)=>Promise.resolve(),
  put:(id: string)=>Promise.resolve(),  
}

UPDATE

Your RecordModel.findOneAndUpdate(data) should receive 0 arguments:

RecordModel.findOneAndUpdate() or RecordModel.findOneAndUpdate(data, other, another)

Please get familiar with mongoose docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM