简体   繁体   中英

Im trying to update my SQL data base with a Sequelize post request with express

I'm trying to update my SQL data base with a Sequelize post request with express. However When I clicked the Update but in respective route it does not work. The app is a simple online library app that lets the user create, update and delete books. I cant get the update or delete parts of the app to work. Being that both of these are post routes I'm assuming I'm doing something very wrong here.

routes/books.js

const express = require('express');
const router = express.Router();
const Book = require('../models').Book;

function asyncHandler(cb){
  return async(req, res, next) => {
    try {
      await cb(req, res, next)
    } catch(error){
      res.status(500).send(error);
    }
  }
}


// Shows the full list of books.
router.get('/', asyncHandler(async (req, res, next) => {
  try {
    const books = await Book.findAll({ order: [["createdAt", "DESC"]]});
    res.render('index', { books, title: "Book list" });
    console.log('Rendering books');
  } catch(e) {
    console.log(e);
  }
 
}));

// Shows the create new book form.
router.get('/new', asyncHandler(async (req, res) => {
  res.render('new-book', {book: {}, title: "New Book"});
}));

/// Posts a new book to the database and redirects to the new route.
router.post('/', asyncHandler(async (req, res, next) => {
  const book = await Book.create({
    title: req.body.title,
    author: req.body.author,
    genre: req.body.genre,
    year: req.body.year })
    res.redirect("/books/" + book.id);
  console.log('Posting books new');
}));

// Shows book detail form.
router.get("/:id", asyncHandler(async (req, res) => {
  const book = await Book.findByPk(req.params.id);
  if(book) {
    res.render("book-detail", { book, title: book.title });  
  } else {
    res.sendStatus(404);
  }
})); 

// Updates book info in the database.
router.post('/', asyncHandler(async (req, res) => {
  const book = await Book.findByPk(req.params.id);
  if (book) {
    await book.update(req.body);
    res.redirect("/books");
  } else {
    res.sendStatus(404);
  }

}));
 
// Deletes a book. 
router.post('/:id/delete', asyncHandler(async (req ,res) => {
  const book = await Book.findByPk(req.params.id)
  if(book) {
    await book.destroy();
    res.redirect("/books");
  } else {
    res.sendStatus(404);
  }
}));

module.exports = router;



routes/index.js

const express = require('express');
const router = express.Router();

/* GET home page. */
router.get('/', (req, res, next) => {
  res.redirect("/books")
});

module.exports = router;

model/book.js (This is the module for the sequelize properties)

const express = require('express');
const Router = require('Router');
const Sequelize = require('sequelize');
'use strict';
module.exports = (sequelize) => {
    class Book extends Sequelize.Model {
      
    }
    Book.init({
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
          },
          title: {
            type: Sequelize.STRING,
            allowNull: false, // disallow null
            validate: {
              notEmpty: {
                msg: 'Please provide a value for "title"'
              }
             }
          },
          author: {
            type: Sequelize.STRING,
            allowNull: false, // disallow null
            validate: {
              notEmpty: {
                msg: 'Please provide a value for "author"'
              }
             }
          },
          genre: {
            type: Sequelize.STRING,
            allowNull: false, // disallow null
            validate: {
              notEmpty: {
                msg: 'Please provide a value for "genre"'
              }
             }
          },
          year: {
            type: Sequelize.INTEGER,
            allowNull: false, // disallow null
            validate: {
              notEmpty: {
                msg: 'Please provide a value for "year"'
              }
             }
          }
       }, { sequelize })
    return Book
}

views/book-detail.pug

extends layout.pug

block content
    h1(class='title') Update Book
    form(action="/books/" + book.id, method="post")
    p
        label(for='title')= book.title
        input#title(name='title' type='text' value= book.title)
    p
        label(for='author')= book.author
        input#author(name='author' type='text' value= book.author)
    p
        label(for='genre')= book.genre
        input#genre(name='genre' type='text' value= book.genre)
    p
        label(for='year')= book.year
        input#year(name='year' type='text' value= book.year)
    p
        input(type='submit' value='Update Book' method='post')
    form(method="post", action="/books/" + book.id, onsubmit="return confirm('Do you really want to delete this book?');")         
    p
        a.button(href='/') ← Home
    p
        input(type='submit' value='Delete Book')
    

I think the problem is that your primaryKey is an integer, and req.params.id is a string. You'll need to parse it first. Once you do that, sequelize should be able to find the Book instance you're looking for.

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