【问题标题】:Fetching data after performing update using Bookshelf.js使用 Bookshelf.js 执行更新后获取数据
【发布时间】:2017-06-16 02:19:28
【问题描述】:

我正在使用save() 方法 (Bookshelf.js) 来更新 PostgreSQL 中的数据。我想在更新后获取完整的模型(所有列)我该怎么做?在我看来 save() 方法只返回 id 和更新的列。我可能做错了,所以任何指导将不胜感激。谢谢。

【问题讨论】:

    标签: javascript node.js postgresql bookshelf.js


    【解决方案1】:

    在 Sequelizejs 中,我们使用这种方法只需在操作成功执行时调用 then 函数中的任何模型。同样的瘦你可以在这里尝试

    new Author({id: 1, first_name: 'User'})
      .save({bio: 'Short user bio'}, {patch: true})
      .then(function(model) {
        //two approach 
    //try this but not sure work in Bookshelf or not
        return model.fetchAll();
    //or u can try 
               new Article().fetchAll()
                .then(function(articles) {
                     res.send(articles.toJSON());
                }).catch(function(error) {
              res.send('An error occured');
        });
    
          });
    

    【讨论】:

      【解决方案2】:

      .save() 书架方法在attributes 字段中返回更新后的对象。

      new User().save({ firstname: 'Foo', lastname: 'Bar' })
      .then(data => {
        console.log(data.attributes);
      
        // You can also do this to remove Bookshelf Model methods
        data = data.toJSON();
        console.log(data);
      });
      

      【讨论】:

        【解决方案3】:

        如果我理解正确的话。您想要获取刚刚更新的行的所有列。然后你可以这样做:

        User.where({ name: name }).fetch().asCallback(function(err, existingEntry){
          if(existingEntry){
              existingEntry.save({ 
                  address: address,
              }).asCallback(function(err, updatedColumns){
                  console.log(existingEntry); // Here you will get all the columns of the updated row
                  console.log(updatedColumns); // Here you can get the columns that you have just updated
              })
          }
        })
        

        如果我提到的情况适用于所有人,则为我工作。此代码的另一件事是书架版本 0.8.2。不要误会

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-25
          • 1970-01-01
          • 1970-01-01
          • 2016-02-29
          • 2015-11-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多