【问题标题】:Strongloop : Compare old model with the new instance in operation hook 'before save'Strongloop:将旧模型与操作钩“保存前”中的新实例进行比较
【发布时间】:2015-06-02 03:32:36
【问题描述】:

我在我的代码中实现了一个“保存前”操作挂钩,以将要保存的新实例与数据库中已有的旧实例进行比较。 为此,我将 ctx.data 中给出的值与数据库中查询给出的值进行比较。 问题是返回的值总是相似的,就好像新实例已经保存在数据库中一样。 我是否完全错过了“保存前”钩子的要点,还是有办法比较这两个值?

module.exports = function(app) {

var Like = app.models.Like;

Like.observe('before save', function(ctx, next) {

    var count = 0;
    if (ctx.instance) { // create operation
        console.log('create operation);
    }
    else { // update operation
        // Query for the existing model in db
        Like.findById(ctx.where.id,
            function(err, item) {
                if (err)
                    console.log(err);
                else {//compare query value and instance value
                    if (item.value != ctx.data.value) {
                        // Always false
                    }
                    else {
                        //Always true
                    }
                }
            }
        );
    }
    next();

我不明白为什么 item.value 总是与 ctx.data.value 相似,因为第一个应该是数据库中的实际值,第二个应该是要保存的值。

【问题讨论】:

    标签: loopbackjs strongloop


    【解决方案1】:

    他们在底部设置 next() 的方式似乎不正确,并且可能会在 findById 调用返回之前提供足够的时间让保存实际发生。一旦你调用了next,保存就可以真正发生,所以findById可以与你的保存竞争。

    尝试这样,您的 next() 在来自 findById 的回调中,这将阻止保存,直到您完成比较。

    module.exports = function(app) {
    
    var Like = app.models.Like;
    
    Like.observe('before save', function(ctx, next) {
    
        var count = 0;
        if (ctx.instance) { // create operation
            console.log('create operation);
            next();
        }
        else { // update operation
            // Query for the existing model in db
            Like.findById(ctx.where.id,
                function(err, item) {
                    if (err)
                        console.log(err);
                    else {//compare query value and instance value
                        if (item.value != ctx.data.value) {
                            // Always false
                        }
                        else {
                            //Always true
                        }
                    }
                next();
                }
            );
        }
    

    【讨论】:

    • 解决了,谢谢。刚接触 javascript,不考虑异步编程...
    猜你喜欢
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多