2017-08-28 169 views
0

我正在研究圖書館API,供用戶借閱和更新。如何使用sequelize.js查詢特定ID以便我可以更新

這是我的借書邏輯:

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

該工程確定(我認爲)一點書,但如果用戶借用2本或更多本書,我嘗試返回它們,但它不起作用。

它如何工作,以便它會返回更多借書的實例。它怎麼能注意到借來的新書的新標識?

如果我嘗試返回第二本書,它會引發以下錯誤?

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: 
+0

請別人幫我出來 – letmebe

回答

相關問題