【问题标题】:Multiple insert Couchbase with node.js使用 node.js 多次插入 Couchbase
【发布时间】:2014-04-02 16:06:59
【问题描述】:

我正在尝试在couchbase中插入多条记录,刚才我使用的是官方的node-couchbase驱动。

var db = new couchbase.Connection({host: hostname, bucket: myBucket, password: pass}, function(error){
        console.log(error);
    });

    var g = guid.raw()
    var a = [];

    for(var i=0; i<100; i++){
        new_beer = {
           "iteration" : i,
           "category": "North American Ale"
        }
        a.push(new_beer);
    }

    console.log(guid);
    db.set(g, a, function(err, result) {
      console.log(err);
    });

只是在插入中,只插入1个元素,我认为那是因为g(所有寄存器的guid值都相同。我如何才能在1个请求中插入这100个寄存器?

【问题讨论】:

    标签: node.js couchbase


    【解决方案1】:

    首先,您应该为每个项目生成一个 guid:

    var docs = {};
    for(var i=0; i<100; i++){
        var guid = guid.raw();
        docs[guid] = {
           "iteration" : i,
           "category": "North American Ale"
        }
    }
    

    然后您可以使用 setMulti (see docs here) 将所有数据存储在一个请求中。

    db.setMulti(docs, {}, function(err, results) {
      if (err) throw err;
    });
    

    【讨论】:

    【解决方案2】:

    在最新版本的 Couchbase 中,NodeJs SDK 在内部进行批处理,因此不需要批处理,并且批处理多 API 已被删除。

    参考 NodeJS SDK 2.6 - Batching Operations 。同样适用于未来的 SDK 3。

    Node.js is an asynchronous language. Since the user is free to dispatch as many operations as they wish, which will be in parallel implicitly, there is no need to batch operations. In fact, if you schedule several asynchronous operations at the same time, then they will be performed at the same time, as the SDK effectively batches them internally. 
    

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多