gpt4 book ai didi

javascript - 在 Meteor 中批量创建

转载 作者:行者123 更新时间:2023-11-30 06:59:11 25 4
gpt4 key购买 nike

我需要在 Meteor 中一次创建 2000 个文档。我知道我可以使用

for (i=0; i<2000; i++) {
CollectionName.insert({});
}

但我希望 Meteor 中有批量创建功能。如何以最快的方式插入这 2000 行?

最佳答案

Meteor 本身不支持这个。但是,它确实允许您访问 Node Mongodb 驱动程序,该驱动程序可以在 native 执行批量插入。

您只能在服务器上执行此操作:

var x = new Mongo.Collection("xxx");

x.rawCollection.insert([doc1, doc2, doc3...], function(err, result) {
console.log(err, result)
});

或者如果您的 Meteor 实例可以访问它,则使用 MongoDB 2.6:

var bulk = x.initializeUnorderedBulkOp();

bulk.insert( { _id: 1, item: "abc123", status: "A", soldQty: 5000 } );
bulk.insert( { _id: 2, item: "abc456", status: "A", soldQty: 150 } );
bulk.insert( { _id: 3, item: "abc789", status: "P", soldQty: 0 } );
bulk.execute( { w: "majority", wtimeout: 5000 } );

注意事项:

  • 这不是同步的,也不是在纤程中运行,因为它使用原始 Node 驱动程序。您需要使用 Meteor.bindEnvironment 或 Meteor.wrapAsync 来创建同步代码
  • 文档是无序插入的,可能与您添加它们的原始顺序不同。
  • 如果您的实例未启用 oplog,Meteor 可能需要 10 秒才能通过发布方法“响应式(Reactive)”查看文档。

关于javascript - 在 Meteor 中批量创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31131127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com