简体   繁体   中英

CouchDB connection

I try to connect to a CouchDB, but I can't seem to find a clear explanation about it anywhere. This is what I tried in C#, but it doesn't do anything at all.

using (var db = new MyCouch.Client("http://127.0.0.1:5984/db"))
        {
            var db = "{'_id': '1', '$doctype': 'db', 'name': '1'}";
            var response = db.Documents.Post(db);
            Console.Write(response.GenerateToStringDebugVersion());
        }

Could someone explain me how to connect and how to simply insert data?

The simple method of connecting to CouchDB is by using System.Net.Http.HttpClient and side-stepping a client library per se (although there are some good ones).

Because the CouchDB API is HTTP, GET, PUT POST and DELETE are the main methods you will need, an example of a generic method wrapping PUT is included below, using native JSON serialiser to accept a POCO model T and write it as a document (Serialisation exception handling omitted for clarity)

    public async Task<R> Put<T, R>(T docObject)
    {  
       string DbName = "demodb";
       string NewDocId = "newDocId";

       // Valid paths, methods and response codes are documented here: http://docs.couchdb.org/en/stable/http-api.html

       using (var httpClient = new HttpClient())
       {
          httpClient.BaseAddress = new Uri("http://server:5984/");
          httpClient.DefaultRequestHeaders.Accept.Clear();
          httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

          // NB: PutAsJsonAsync is an extension method defined in System.Net.Http.Formatting
          var response = await httpClient.PutAsJsonAsync(DbName + "/" + NewDocId, docObject);
          R returnValue;
          if (response.StatusCode == HttpStatusCode.OK)
          {
             returnValue = await response.Content.ReadAsAsync<R>();
          }
          // Check the docs for response codes returned by each method.  
          // Do not forget to check for HttpStatusCode.Conflict (HTTP 409) and respond accordingly.
       }
   }

To complete the example, the return type R should be something the properties of the JSON response coming back from CouchDB can be deserialised into, eg

public class CreateResponse
{
    // use of JsonPropertyAttribute is supported on properties if needed.
    public bool ok { get; set; }
    public string id { get; set; }
    public string rev { get; set; }
    public string error { get; set; }
    public string reason { get; set; }
}

If using basic authentication, you can prefix the server Url with your credentials such as: http://user:pass@server/ If using Cookie authentication, set up a HttpClientHandler with a new CookieContainer and pass the handler to the HttpClient constructor.

Two final notes:

  • Check the difference between submitting PUT /db/newid vs. POST /db for creating docs
  • Also have a look at the bulk docs API if you need to create multiple docs on the same request (ie group new docs on the same request to get ACID insert of multiple docs).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM