首页 > 解决方案 > 如何使用 TYPEORM 更新数据库中的项目?

问题描述

试图更新我的数据库的标题和描述参数。

我已经成功地为我的数据构建了 post 并获取了路由,但是当我在 Postman 上测试 put 路由时,仍然遇到一般的 500 错误。我知道我的控制器一定有问题。

我的进口:

import { NextFunction, Request, Response, Router } from 'express'
import { isEmpty } from 'class-validator'
import { getRepository } from 'typeorm'
import multer, { FileFilterCallback } from 'multer'
import path from 'path'
import fs from 'fs'

import User from '../entities/User'
import Sub from '../entities/Sub'

我的路由:

const router = Router()

router.put('/:name', updateSub)

我的控制器:

const updateSub = async (req: Request, res: Response) => {
  const name = req.params.name
  const { description, title } = req.body
  
  try {
    const subUpdate = await Sub.update(name, { description, title })
    return res.json(subUpdate)
  } catch (err) {
    console.log(err)
    return res.status(500).json({ error: 'Something went wrong' })
  }
}

编辑添加了 Sub.ts 实体:

import {
    Entity as TOEntity,
    Column,
    Index,
    ManyToOne,
    JoinColumn,
    OneToMany,
  } from 'typeorm'
  
  import Entity from './Entity'
  import User from './User'
  import Post from './Post'
  import { Expose } from 'class-transformer'
  
  @TOEntity('subs')
  export default class Sub extends Entity {
    constructor(sub: Partial<Sub>) {
      super()
      Object.assign(this, sub)
    }
  
    @Index()
    @Column({ unique: true })
    name: string
  
    @Column()
    title: string
  
    @Column({ type: 'text', nullable: true })
    description: string
  
    @Column({ nullable: true })
    imageUrn: string
  
    @Column({ nullable: true })
    bannerUrn: string
  
    @Column()
    username: string
  
    @ManyToOne(() => User)
    @JoinColumn({ name: 'username', referencedColumnName: 'username' })
    user: User
  
    @OneToMany(() => Post, (post) => post.sub)
    posts: Post[]

标签: node.jsrestexpresstypeormput

解决方案


推荐阅读