Loopback 模型中的 findOrCreate

findOrCreate in Loopback model

我在环回上发现了一个有趣的问题。我在使用 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 条。

有什么问题吗?

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

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