4

I am using WatermelonDB as a local database of my app. I have a method getPlaces() inside a class AccessDB:

static async getPlaces() {
        const postsCollection = database.collections.get('places');
        const allPosts = await postsCollection.query().fetch();
        return allPosts;
}

Calling getPlaces() using AccessDB.getPlaces() with async and await works. How can I fetch the results matching the query?

radex
  • 6,336
  • 4
  • 30
  • 39
j.Doe
  • 202
  • 4
  • 18

2 Answers2

1

The variable allPosts is an array with all places in your case. So to access the properties of the places, you would do in a different class:

import AccessDB from './AccessDB';

and then somewhere for example

(async () => {
    try {
        const places = await AccessDB.getPlaces();

        var buffer = '';
        for (place in places) {
            buffer += places[place].name + '\n'
        }
        console.log(buffer)
    } catch(e) {console.log(e)}
})()

You have to be carefully when debugging with console.log, as

1) console.log skips outputs if executed fast one after the other, e.g. if you console.log the places[place].name every time in the for-loop above and

2) if you console.log(places) you see the same as if you console.log(database) which is very confusing. You would expect to see [Object object],[Object object]..., which you see when you use alert(places).

TheRuedi
  • 122
  • 1
  • 7
0

Maybe I am not understanding fully. But did you try to put query inside your query method

const allPosts = await postsCollection.query(Q.where('is_verified', true)).fetch();

Also do not forget that getPlaces is async and your need async\await to get return data.

Talgat Saribayev
  • 1,898
  • 11
  • 19
  • When I printed `allPosts`, I realized, that `allPosts` equals my database object. I.e `database.collections.get('places') = database` Why isn't it extracting those places? – j.Doe Feb 24 '19 at 20:02