Updating and Deleting documents using NodeJS on Cloudant DB

有些话、适合烂在心里 提交于 2019-12-13 18:05:59

问题


I was able to successfully query(select) and insert data into Cloudant database using HTTP /REST API. But I am not able to figure out - how to delete and modify documents.

For Delete: I tried the following code in nodejs path : '/quick_loan_nosql_db_1?951b05d1b6aa100f4b94e5185674ef40/_rev=1-88963c755157188091f0d30115de18ce' part of the REST API Request with METHOD: DELETE. But when I execute it deletes the entire database instead of the ID being specified.

For Update: Can some one provide a sample, I tried with PUT, but in response I got a Conflict data error. Any input would be appreciated.


回答1:


Nice! To answer your original question, you just have the "/" and the "?" in the wrong places. To recap:

/quick_loan_nosql_db_1?951b05d1b6aa100f4b94e5185674ef40/_rev=1-88963c755157188091f0d30115de18ce

should instead be:

/quick_loan_nosql_db_1/951b05d1b6aa100f4b94e5185674ef40?_rev=1-88963c755157188091f0d30115de18ce




回答2:


Here is one way I figured out to perform the Update and Delete.

I used nano api:

Include nano by var nano =require('nano')('https://'+dbCredentials.user+':'+dbCredentials.password+'hostname:port/'); Please make sure to put the right user id and password

For Update

Update - you need to use insert api only, but with the right _id and _eval and the changes. For example:

 nanodb.insert({ "_id": "3a1cc8c7f955f895131c3289f5144eab", "_rev": "2-    7040205a1c9270ad696724458399ac94",  "name": "Tom", "employername":"Google"},      function(err, body, header) {
if (err) {
    console.log('[db.insert] ', err);
    return;
  }
  console.log('you have inserted the rabbit.')
  console.log(body);
});

The above code will perform an update on the given id and the _rev. There will be a new revision number updated and the id will remain same. If you miss the ID or revision number, it will throw a conflict error.

For Delete Simple use nano.destroy with the id and the revision number

nanodb.destroy("3a1cc8c7f955f895131c3289f5144eab","3-3e39e2298f109414cef1310449e0fd5c",function(err, body, header) {
    if (err) {
    console.log('[db.insert] ', err);
    return;
  }
  console.log('you have inserted the rabbit.')
  console.log(body);

    });

Using Nano like framework API is better than making REST API calls over http for accessing the cloudant Database.

Hope this helps for people who want to connect to Cloudant db from NodeJS



来源:https://stackoverflow.com/questions/33199842/updating-and-deleting-documents-using-nodejs-on-cloudant-db

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