【问题标题】:How to update a model? .updateAttributes is not a function如何更新模型? .updateAttributes 不是函数
【发布时间】:2018-11-03 02:32:27
【问题描述】:

我正在构建一个 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 部分时,我得到了当前状态的响应。

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

【问题讨论】:

    标签: node.js postgresql express sequelize.js


    【解决方案1】:

    您应该将 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 并知道如何使用它,请试试这个并阅读 cmets,这将消除你所有的疑惑:

    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 });
        });
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      相关资源
      最近更新 更多