我正在构建一个 Node Express 应用程序,使用 Postgres 作为 DB,使用 Sequelize 作为 ORM。
我有一个 router.js
文件:
router.route('/publish')
.put((...args) => controller.publish(...args));
controller.js
看起来像这样:
publish(req, res, next) {
helper.publish(req)
.then((published) => {
res.send({ success: true, published });
});
}
还有一个helper.js
publish(req) {
return new Promise((resolve, reject) => {
Article.findAll({
where: { id: req.query.article_id },
attributes: ['id', 'state']
})
.then((updateState) => {
updateState.updateAttributes({
state: 2
});
})
.then((updateState) => {
resolve(updateState);
});
});
}
例如,当我点击 PUT http://localhost:8080/api/publish?article_id=3555
我应该得到:
{
"success": true,
"published": [
{
"id": 3555,
"state": 2
}
]
}
文章当前状态为1。
但是,我收到以下错误 Unhandled rejection TypeError: updateState.updateAttributes is not a function
。当我从我的 helper.js 中删除 updateState.updateAttributes
部分时,我得到了当前状态的响应。
如何正确更新文章状态?
最佳答案
您应该将 findAll
更改为 findOne
,因为您只是想通过 id 查找特定文章:
Article.fineOne({ //<--------- Change here
where: { id: req.query.article_id },
attributes: ['id', 'state']
})
.then((updateState) => {
updateState.updateAttributes({state: 2}); //<------- And this will work
})
但是如果你仍然想使用 findAll 并想知道如何使用它,请尝试这个并阅读评论,这将消除你所有的疑虑:
Article.findAll({
where: { id: req.query.article_id },
attributes: ['id', 'state']
})
.then((updateState) => {
// updateState will be the array of articles objects
updateState.forEach((article) => {
article.updateAttributes({ state: 2 });
});
//-------------- OR -----------------
updateState.forEach((article) => {
article.update({ state: 2 });
});
})
关于node.js - 如何更新模型? .updateAttributes 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499596/