2

I'm trying to add (aka. push to existing array) in couchDB document. Any feedback is greatly appreciated.

I have a document called "survey" inside my database called "database1". I have "surveys" as a set of arrays which consists of objects that has information on each survey.

My goal is to update my "survey" document. Not replacing my array, but adding a new object to the existing array. I've used "nano-couchdb" and "node-couchdb", but could not find a way around it. I was able to update my "surveys", but it would replace the whole thing, not keeping the existing objects in array.

1) Using Nano-couchdb:

db.insert({ _id, name }, "survey", function (error, resp) { 
  if(!error) { console.log("it worked")
  } else { 
  console.log("sad panda")} 
})

2) Using couchdb-node:

couch.update("database1", {  
  _id: "survey", 
  _rev:"2-29b3a6b2c3a032ed7d02261d9913737f", 
  surveys: { _id: name name: name } 
)

These work well with adding new documents to a database, but doesn't work with adding stuff to existing documents.

    {
      "_id": "survey",
      "_rev": "2-29b3a6b2c3a032ed7d02261d9913737f",
      "surveys": [
        {
          "_id": "1",
          "name": "Chris"
        },
        {
          "_id": "2",
          "name": "Bob"
        },
        {
          "_id": "1",
          "name": "Nick"
        }
        ]
    }

I want my request to work as it would for

"surveys.push({_id:"4",name:"harris"}) 

whenever new data comes in to this document.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Harris Lee
  • 93
  • 1
  • 2
  • 7

1 Answers1

0

Your data model should be improved. In CouchDB it doesn't make much sense to create a huge "surveys" document, but instead store each survey as a separate document. If you need all surveys, just create a view for this. If you use CouchDB 2.0, you can also query for survey documents via Mango.

Your documents could look like this:

{
  "_id": "survey.1",
  "type": "survey",
  "name": "Chris"
}

And your map function would look like that:

function (doc) {
  if (doc.type === 'survey') emit(doc._id);
}

Assuming you saved this view as 'surveys' in the design doc '_design/documentLists', you can query it via http://localhost:5984/database1/_design/documentLists/_view/surveys.

Bernhard Gschwantner
  • 1,547
  • 11
  • 12