Strongloop:在“保存之前"将操作钩子中的旧模型与新实例进行比较

编程入门 行业动态 更新时间:2024-10-28 15:30:20
本文介绍了Strongloop:在“保存之前"将操作钩子中的旧模型与新实例进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

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.

推荐答案

以这种方式在底部显示next()似乎不正确,并且可能给了足够的时间使保存真正发生在findById调用之前返回.呼叫next后,实际上可以进行保存,因此findById可以与您的保存竞争.

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.

尝试这种方法,其中next()在findById的回调中,这将阻止保存,直到完成比较为止.

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

更多推荐

Strongloop:在“保存之前"将操作钩子中的旧模型与新实例进行比较

本文发布于:2023-10-13 14:36:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1488231.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:钩子   实例   模型   操作   Strongloop

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!