带有node.js的多个插入Couchbase

时间:2014-04-02 16:07:00

标签: node.js couchbase

我正在尝试在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个寄存器?

2 个答案:

答案 0 :(得分:3)

首先,你应该为每个项目生成一个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;
});

答案 1 :(得分:0)

在最新版本的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.