Strongloop : Compare old model with the new instance in operation hook 'before save'

泪湿孤枕 提交于 2020-01-16 18:33:34

问题


I implemented a "before save" operation hook in my code to compare the new instance about to be saved with the old one already in the database. For that, I compare the value given in the ctx.data with the one given by a query in the database. The problem is the returned values are always similar, as if the new instance has already been saved in the database. Have I totally missed the point of the "before save" hook, or is there a way to compare the two values ?

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

I can't understand why item.value always similar to ctx.data.value as the first one is supposed to be the actual value in the db and the second one the value about to be saved.


回答1:


They way you have next() at the bottom doesn't seem right and might be giving enough time for the save to actually happen before the findById call returns. Once you call next the save can actually happen so findById can race with your save.

Try it like this where your next() is within the callback from the findById which will block saving until you've done your comparison.

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


来源:https://stackoverflow.com/questions/29323833/strongloop-compare-old-model-with-the-new-instance-in-operation-hook-before-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!