我正在开发图书馆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
}))
})
}
})
}
这对于一本书来说是可行的(我认为),但是如果用户借了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 :(得分:0)
您是否尝试过使用.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
}
})
取决于您是否要使用实例模型或原始值,您必须传递一些选项。即:raw:true