Is there a method to insert multiple documents in one query?


#1

Hi,

I’m lookin for a way with couchebase-node to insert multiple documents at the same time.

Like that I don’t have to wait each fallback before inserting the other document or create a recursive function:

This is an example of what I’m currently doing:

Describe how to update userdatas within the UserModel

describe “UserModel:deleteUser()”, ->

Define the set of 3 users who will try to access the data user

wantedUserId = ""
adminUserId = ""
hackerUserId = “”

Define the database object

db = {}
before (done) ->
# Create the data base connection
db = new couchbase.Connection
host: 'localhost:8091’
bucket: ‘test’

# Create the user we are looking for
wantedUser = utils.support.get_user_args() 
wantedUserId = "user:#{utils.support.random.number()}"

# Create the requester user with admin rights
adminUser = utils.support.get_user_args
  rights: ['admin']
adminUserId = "user:#{utils.support.random.number()}"

# Create the requester user without the admin rights
hackerUser = utils.support.get_user_args()
hackerUserId = "user:#{utils.support.random.number()}"

# Insert 1st user in the data base
db.add wantedUserId, wantedUser, (err, results) ->
  # Insert 2nd user in the data base
  db.add adminUserId, adminUser, (err, results) ->
    # Insert 3rd user in the data base
    db.add hackerUserId, hackerUser, (err, results) ->
      done()

I would to know if there is a solution to get something like that instead:

db.add( [{ _id: wantedUserId document: wantedUser }, { _id: adminUserId document: adminUser }, { _id: hackerUserId document: hackerUser }], (err, results) -> done() )

Thanks.


#2

Even though there is no direct support in the SDK you can use the async library to do what you want. As a small example I create a little script which inserts 100 documents in parallel. Depending on your needs you should also look into async series and so on.

var couchbase = require("couchbase") var async = require("async")

var db = new couchbase.Connection({})

// create insert function which expects just a callback
function insertFormObject(object) {
return function (cb) {
db.set(object._id, object.value, cb)
}
}
// create array of inserts
var documents = [
{ _id: “mykey-0”, value: { iam: “adoc” } },
{ _id: “mykey-1”, value: { iam: “adoc” } },
{ _id: “mykey-2”, value: { iam: “adoc” } },
{ _id: “mykey-3”, value: { iam: “adoc” } }
]
var inserts = documents.map(function(o) { return insertFormObject(o) })

// run all inserts in parallel
async.parallel(inserts, function(err) {
if(err) new Error(err);
db.shutdown();
})

You can find the gist on github as well hope this helps.


#3

Hi,
Thanks for your answer

I have found the solution in the SDK directly (setMulti, addMulti, etc…).

documents =
“doc::1”:
value : {DOC1}
“doc::2”:
value: {DOC2}

db.addMulti documents, {}, (err, results) ->
db.shutdown()