1

like this

{
 id:1,
 name:john, 
 role:[
  {name:boss, type:xyz}, 
  {name:waiter, type:abc}
 ]
} 

i want to add array of objects to "role" without losing other data, but new data should add to array as a objects.

i have tried with

bucket.upsert(key, data, (error: CouchbaseError | null, result: any) => {})

where key is a id of document and data is {name:boss, type:xyz} it shows key already exist.

for db.upsert it replace whole data with new data.

var query = N1qlQuery.fromString('UPDATE `myBucket` SET role = ' + '"' + data + '"' + ' WHERE meta().id =' + '"' + key + '"');

above code shows role:[object object] in database.

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
Payal
  • 11
  • 3

1 Answers1

1

First, I'd think about upgrading to 3.x for the Couchbase Node SDK.

Second, I think what you're looking for is the subdocument API, specifically the "array append" operation. This allows you to make changes to parts of a document Here's an example from the 2.6 docs:

bucket
  .mutateIn('customer123')
  .arrayAppend('purchases.complete', 777)
  .execute(function(err, res) {
    // purchases.complete is now [339, 976, 442, 666, 777]
  });

I'm not much of a Node/JavaScript developer, but I would assume for your example, it would be something like this:

bucket
  .mutateIn('1')
  .arrayAppend('role', theNewRoleYouWantToAdd)
  .execute(function(err, res) {
    
  });

Side note: For your N1QL example, the reason that [object object] is showing up is probably related to your data object returning that as a string. You should also look up "SQL injection", because N1QL code like that could be susceptible. Look into placeholders and parameterization.

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
  • thanks for above solution. i have tried that but it is showing ".mutateIn does not exist on type bucket" , not getting exact issue as i m new to couchbase. kindly suggest solution for above issue. thank you. – Payal May 07 '21 at 21:40
  • @softwaredeveloper you've reached the limit of my Node/JS knowledge, so I've asked someone else from Couchbase to take a look. – Matthew Groves May 10 '21 at 13:55