如何更新模型?.updateAttributes不是函数

Tom*_*omb 3 postgresql node.js express sequelize.js

我正在构建一个Node Express应用程序,其中Postgres作为数据库,Sequelize作为ORM。

我有一个router.js文件:

router.route('/publish')
  .put((...args) => controller.publish(...args));
Run Code Online (Sandbox Code Playgroud)

controller.js 看起来像这样:

publish(req, res, next) {
  helper.publish(req)
  .then((published) => {
    res.send({ success: true, published });
  });
}
Run Code Online (Sandbox Code Playgroud)

还有一个 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);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

因此,例如,当我按下PUT时,http://localhost:8080/api/publish?article_id=3555我应该得到:

{
  "success": true,
  "published": [
    {
      "id": 3555,
      "state": 2
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

该文章的当前状态为1。

但是,出现以下错误Unhandled rejection TypeError: updateState.updateAttributes is not a function。当我updateState.updateAttributes从helper.js中删除该部件时,会得到当前状态的响应。

如何正确更新文章的状态?

Viv*_*shi 6

你应该改变findAllfindOne,因为你只是想通过ID查找特定的文章:

Article.fineOne({  //<--------- Change here
    where: { id: req.query.article_id },
    attributes: ['id', 'state']
})
.then((updateState) => {
    updateState.updateAttributes({state: 2}); //<------- And this will work
})
Run Code Online (Sandbox Code Playgroud)

但是,如果您仍然想使用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 });
    });
})
Run Code Online (Sandbox Code Playgroud)