【问题标题】:Im trying to update my SQL data base with a Sequelize post request with express我正在尝试使用带有 express 的 Sequelize 发布请求来更新 mySQL 数据库
【发布时间】:2020-06-29 23:31:35
【问题描述】:

我正在尝试使用 Express 的 Sequelize 发布请求更新我的 SQL 数据库。但是,当我单击更新但在各自的路线中它不起作用。该应用程序是一个简单的在线图书馆应用程序,允许用户创建、更新和删除书籍。我无法让应用程序的更新或删除部分工作。由于这两个都是发布路线,我假设我在这里做错了。

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;



路由/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(这是sequelize属性的模块)

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')
    

【问题讨论】:

    标签: javascript node.js express sequelize.js pug


    【解决方案1】:

    我认为问题在于您的 primaryKey 是一个整数,而 req.params.id 是一个字符串。你需要先解析它。一旦你这样做了,sequelize 应该能够找到你正在寻找的 Book 实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多