我正在开发一个图书库 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 本书或更多书,我尝试归还它们,它不起作用。
它如何工作才能返回更多借书实例。它如何注意到新借来的书的新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
}
})
根据您是要使用实例模型还是原始值,您必须传递一些选项。即:原始:真实
关于javascript - 如何使用 sequelize.js 查询特定 ID 以便我可以更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45923887/