【问题标题】:Updating a waterline model from an instance method从实例方法更新水线模型
【发布时间】:2016-12-18 05:48:48
【问题描述】:

我正在使用 Waterline ORM 与我的数据库交互。

我将 Waterline.Collections 扩展为一个新对象并将它们分配给一个模块:

var Waterline = require('waterline');

var User = Waterline.Collection.extend({
    ...some fields...
    attributes:{
        col_a:{
             type:'integer'
        },
        touch_user:function(){
            //   increment col_a and update in table
        }
    }
});

export = module.exports = User;

我查询需要更新的特定模型,然后在 Promise 中操作它们。

database.models.users.findAll().where({'id':1}).then(...model manipulation...)

我经常执行一项任务,几乎每当我访问模型时。我想将此任务封装在与实例关联的函数中,以便我可以简单地调用“touch_user”,并且相关字段将针对我调用它的模型进行更新。

在这样查询模型后,我无法从模型实例访问 Waterline 查询方法(例如 .update()):

database.models.users.findAll().where({'id':1).then((user)=>{
    user.touch_user();
    //user.update    // does not work
});

但直到我查询它,我才检索与记录关联的数据。 我希望 user.touch_user() 在 users 表中增加 col_a ,如下所示

database.models.users.findAll().where({'id':1).then((user)=>{
    user.touch_user();
    database.models.users.update(user.id, {'col_a':user.col_a+1});
});

上面的问题是用户对象没有准确地反映对表的更新。

【问题讨论】:

    标签: node.js waterline


    【解决方案1】:

    我最终做的是创建一个类方法来更新模型和实例。不完全是我想要的,但它确实可以让模型和表格保持同步

    var User = Waterline.Collection.extend({
        ...some fields...
        attributes:{
             col_a:{
                  type:'integer'
             },
         },
         //  touch_user is a class method here
         touch_user:function(user){
             // update model instance
             user.col_a += 1;
             // update database table
             database.models.users.update(user.id, {'col_a':user.col_a).exec(function(){});
         }
    });
    

    这样称呼

    database.models.users.findAll().where({'id':1).then((user)=>{
        ...modify user...
        database.models.users.touch_user(user);
    
        ...other changes to user that have to occur here...
        database.models.users.touch_user(user);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      相关资源
      最近更新 更多