Multiple insert Couchbase with node.js

江枫思渺然 提交于 2019-12-23 16:06:12

问题


I'm trying to insert multiple records into couchbase, just now, I'm using the official node-couchbase driver.

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

Just in the insertion, only insert 1 element, I think that is because the g (the guid value is the same for all the registers. How I can insert these 100 registers in 1 only request?


回答1:


First of all you should generate one guid per one item:

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

Then you can use setMulti (see docs here) to store all your data in one request.

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



回答2:


In the latest version of Couchbase, NodeJs SDK does the batching internally, so there is not batching required and the batching multi API has been dropped.

Ref to NodeJS SDK 2.6 - Batching Operations .The same applies for the future SDK 3 as well.

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. 


来源:https://stackoverflow.com/questions/22817112/multiple-insert-couchbase-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!