【问题标题】:findOrCreate in Loopback model环回模型中的 findOrCreate
【发布时间】:2016-07-01 23:19:09
【问题描述】:

我在环回上发现了一个有趣的问题。当我使用findOrCreate 添加记录时,我感到很困惑。我们来看例子:

  for (var x = 0; x < 10; x++) {
    console.log(x);
    var Log = app.models.Log;
    Log.findOrCreate({
      where: {
        modelName: '123'
      }
    }, {
      modelName: '123'
    }, function(err, log) {
      if (err) return;
      if (log) {
        console.log("+ " + log.id);
      }
    });
  }

我认为它应该只使用modelName '123' 创建 1 条记录,但我最终得到了 10 条。

有什么问题吗?

【问题讨论】:

    标签: javascript node.js model loopbackjs strongloop


    【解决方案1】:

    这是意料之中的。您正在同步运行代码。如果您以异步方式运行它,您将看到仅创建一个文档。试试这个:

    var arr = new Array(10);
    async.eachSeries(arr, function (pos, callback) {
        console.log(pos);
        Log.findOrCreate({
          where: {
            txt: '123'
          }
        }, {
          txt: '123'
        }, function (err, log) {
          if (err) return;
          console.log("+ " + log.id);
          callback();
        });
      }, function (err) {
        if (err) {
          throw err;
        }
      }
    );
    

    【讨论】:

    • 你是明星!非常感谢!!
    • 你确定 .findOrCreate() 在过滤器对象中使用 where 键吗?如果我使用.findOrCreate({where: {key: 'value'}}),则创建的对象不包含指定的值,而是 null。但如果我使用.findOrCreate({key: 'value'}),一切似乎都是正确的。在这两种情况下,数据库中的困难项目都正确存储。
    • @Kpihus 关于这个问题的详细讨论请看这篇帖子:github.com/strongloop/loopback-datasource-juggler/issues/766
    猜你喜欢
    • 2018-05-07
    • 2019-03-24
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2015-03-21
    • 2016-06-26
    • 1970-01-01
    相关资源
    最近更新 更多