繁体   English   中英

如何使用sequelize.js查询特定的ID,以便对其进行更新

[英]How can I query a particular ID with sequelize.js so I can update it

我正在开发图书库API,用户可以在其中借用和更新。

这是我借书的逻辑:

BorrowBooks(req, res) {
  Book.findOne({
      where: {
        title: req.body.booktitle,
        author: req.body.author,
      }
    })
    .then(book => {
      if (!book) {
        res.status(404).send({
          message: "Book not found!"
        })
      } else {
        return Borrower
          .create({
            booktitle: req.body.booktitle,
            borrowDate: Date.now(),
            returnDate: null,
            userId: req.params.userId,
          })
          .then(borrower => {
            res.status(200).send(borrower)
            book.update({
              count: book.count - 1,
            });
          })
          .catch((e) => {
            return res.status(400).send(e)
          })
      }
    });
},

要退还书,我需要以下内容:

returnBooks(req, res) {
  Book.findOne({
      where: {
        title: req.body.title,
        author: req.body.author,
      }
    })
    .then((book) => {
      if (!book) {
        return res.status(400).send({
          message: "There is no book like that!"
        })
      } else {
        book.update({
          count: book.count + 1,
        })
        Borrower.findOne({
            where: {
              id: req.params.userId,
              booktitle: req.body.title,
            }
          })
          .then((returnedBook) => {
            returnedBook.update({
                returnDate: Date.now()
              })
              .then(() => res.status(200).send({
                message: "book successfully returned",
                returnedBook
              }))
          })
      }
    })
}

对于一本书,这行得通(我认为),但是,如果用户借用了两本书或更多书,而我尝试退还,则无法使用。

它如何工作,以便返回更多借来的书实例。 它如何注意到借来的新书的新ID?

如果我尝试退还第二本书,则会引发以下错误?

Unhandled rejection TypeError: Cannot read property 'update' of null
    at Borrower.findOne.then (C:\Users\okonjiemmanuel\Desktop\hellobooks\server\controllers\book.js:142:23)
    at tryCatcher (C:\Users\okonjiemmanuel\Desktop\hellobooks\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\Users\okonjiemmanuel\Desktop\hellobooks\node_modules\bluebird\js\release\promise.
js:512:

您是否尝试过使用.findAll?

http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-findAll

Book.findAll({
  where: {
    title: req.body.title,
    author: req.body.author
  }
})

根据您是否要使用实例模型或原始值,您必须传递一些选项。 即:原始:真实

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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