3

Hi I want to create a couchdb database of this format where I can add items in the right type of item(Vegetables or Fruits) enter image description here

But I want to know how can I add some products in the catalog with the nano utils of couchdb without erasing the list of items already created. The actual method to add products in my catalog is this one: but the problem is that I can add only one item to the catalog. I wanted to make a product.get() but how can I add items to the get result and how can I insert the new list to the database?

function AddProduct(name, price, image, category, id) {

  return new Promise((resolve, reject) => {
    var catalog = 'catalog'
  
    catalog.insert(
      // 1st argument of nano.insert()
      {
        "catalog": {
          category: {
            id: {
              'name': name,
              'price': price,
              'image': image,
              'category': category
            }
          }
        }
      }, 'catalog',
      (error, success) => {
        if (success) {
          resolve(name)
        } else {
          reject(
            new Error(`In adding (${name}). Reason: ${error.reason}.`)
          )
        }
      }
    )
  })
}```
  • If the document may exist, you should attempt to get it first. If it does exist add the new item to the existing array, otherwise put the new document. This is not a good schema however, I recommend one document per item, and say have a 'type' field to hold a value such as 'catalog-vegetable', 'catalog-fruit', etc. to facilitate lookup with map/reduce or find. – RamblinRose Nov 15 '21 at 11:58
  • @RamblinRose Thanks but my question is how can I add the new items to the list. I have to use this schema. – a_confused_student_2 Nov 15 '21 at 12:06
  • Use [head](https://github.com/apache/couchdb-nano#dbheaddocname-callback) to determine if the document exists. If it does exist, use [get](https://github.com/apache/couchdb-nano#dbgetdocname-params-callback) and modify the document, otherwise create the document; in both cases use [insert](https://github.com/apache/couchdb-nano#dbinsertdoc-params-callback) to update or add the document. – RamblinRose Nov 15 '21 at 13:50
  • Also, avoid posting images. It prevents people with visual impairments from helping, among other things. – RamblinRose Nov 15 '21 at 13:52

0 Answers0