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

标签 node.js postgresql express sequelize.js

我正在构建一个 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/

相关文章:

javascript - 使用连接角色的 Node.js 角色授权

用C连接Postgresql

javascript - 使用 Node.js 遍历 XML 文档的最快方法?

node.js - 将编译的 typescript 部署到 lambda 时导入模块错误

windows - 在 Windows 平台上连接 Node.js 和 Oracle

postgresql - 从另一个 schema.table.column postgresql 更新列的内容

Postgresql 模式匹配一​​个选择

javascript - 在具有相同参数名称的多个路由中表达 : Calling functions on app. 参数

mysql - JWT 身份验证要求我注销并重新登录才能查看用户的更新信息

node.js - Mongoose 保存文档成功但没有反射(reflect)在数据库中