代码之家  ›  专栏  ›  技术社区  ›  Tom Bom

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

  •  2
  • Tom Bom  · 技术社区  · 6 年前

    我正在构建一个节点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 });
      });
    }
    

    和A 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 . 当我移除 updateState.updateAttributes 部分来自helper.js,我得到当前状态的响应。

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

    1 回复  |  直到 6 年前
        1
  •  5
  •   Vivek Doshi    6 年前

    你应该换一下 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
    })
    

    但是如果你仍然想和芬德尔一起去,并且想知道如何使用它,请试试这个,并阅读评论,这将消除你所有的疑问:

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