Daniel
Daniel

Reputation: 1026

Get documents using find() method in couchdb-nano

Since CouchDB doesn't have any collections, I added a custom typeproperty to my entitys. Now I want to filter all entitys on that property, e.g. get all users by {type:'user'}. In the couchdb-doc I found a method called 'find()', which is also implemented in the nano typings, but have a lack of documentation in couchdb-nano. According to the definition, I wrote the follwing code:

class UserModel {
    type: string = 'User';
    name: string = '';
    mail: string = '';
}
let db = <nano.DocumentScope<UserModel>>nano("http://localhost:5984/testdb");
let query: nano.MangoQuery = { selector: { type: "User" } };
db.find(query, (cb:nano.Callback<nano.MangoResponse<UserModel>>) => {
    // How to get the results here? cb is a callback, but this doesn't make sense
});

It doesn't make sense to me that I get a callback. How can I get the results?

Tried using some kind of callback:

db.find(query, (users: nano.MangoResponse<UserModel>) => {
    console.log(users);
});

But users is undefined, altough the filter { selector: { type: "User" } } works well in Project Fauxton.

Upvotes: 1

Views: 3450

Answers (1)

Megidd
Megidd

Reputation: 7952

As mentioned in the nano documentation:

In nano the callback function receives always three arguments:

  1. err - The error, if any.
  2. body - The HTTP response body from CouchDB, if no error. JSON parsed body, binary for non JSON responses.
  3. header - The HTTP response header from CouchDB, if no error.

Therefore, in the case of db.find you will have:

db.find(query, (err, body, header) => {
    if (err) {
        console.log('Error thrown: ', err.message);
        return;
    }
    console.log('HTTP header received: ', header)
    console.log('HTTP body received: ', body)
});

I didn't work with typescript, however I think you can do the same with typescript.

Upvotes: 4

Related Questions