代码之家  ›  专栏  ›  技术社区  ›  Alexander Mills

批量创建-出错时会发生什么

  •  0
  • Alexander Mills  · 技术社区  · 6 年前

    如果我们使用mongoose模型创建方法:

    Model.create([{foo: 'bar'}, {foo: false}, {foo: 'star'}], (err, result) => {
    
        // should have an error, if foo is supposed to be a string
    
    });
    

    如果插入其中一个文档时出错,是否意味着其余所有文档都会失败?我的猜测是,所有的文件都试图被插入,即使其中一个失败,但我不确定。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Alexander Mills    6 年前

    你必须使用 ordered: false

    Model.create([...], {ordered: false}, (err, result) => {
       // if one fails, other inserts may succeed
    });
    

    与。

    Model.create([...], {ordered: true}, (err, result) => {
        // if one fails, all inserts fail
    });