appy-one / acebase

A fast, low memory, transactional, index & query enabled NoSQL database engine and server for node.js and browser with realtime data change notifications
MIT License
481 stars 27 forks source link

`ref().get()` works while `query().get()` returns an empty array #229

Closed JiPaix closed 1 year ago

JiPaix commented 1 year ago

This might just be me not understanding how AceBase works but i'm getting some weird results between query() and ref()
A brief example of what's happening

const test1 = await db.ref(`users/user_1`).get()
const test2 = await db.query(`users/user_1`).get()

console.log(test1.val()) //=> { username: 'user_1' }
console.log(test2.getValues()) //=> DataSnapshotsArray(0) []

Here's the whole context:

export class UserDatabase extends AceBase {
  static #instance: UserDatabase

  static async getInstance (): Promise<UserDatabase> {
    if (!(this.#instance instanceof UserDatabase)) {
      this.#instance = new this('auth', { logLevel: 'log', storage: { path: '.' } })
      await this.#instance.ready()
      await this.#instance.#userSchemasAndIndexes()
    }
    return this.#instance
  }

  async #userSchemasAndIndexes (): Promise<void> {
    await this.schema.set('users/$uid', {
      username: 'string',
      password: 'string',
      createdAt: 'Date',
      allowed: 'boolean'
    })

    await this.indexes.create('users', 'username')
  }

  static async isAllowed (userId: string): Promise<boolean> {
    const self = await UserDatabase.getInstance()

   /**
    * Ideally this is what i'd like to do:
    * return self.query(`users/${userId)`).filter('allowed', '==', true).exists()
    */

    const ref = await self.ref(`users/${userId}`).get()
    const query= await self.query(`users/${userId}`).get()

    console.log(bb.getValues()) //=> empty array
    console.log(ref.val()) //=> the user obj

    return false //=> false for testing purpose
  }

Then somewhere else in the code is called UserDatabase.isAllowed

const allowed = await UserDatabase.isAllowed('1234')
appy-one commented 1 year ago

ref references a specific entry in your database, where query searches an object collection by matching each child of the referenced path for given filter conditions.

You can simply use ref:

const snapshot = await db.ref(`users/${userId}/allowed`).get();
const isAllowed = snapshot.val() === true;

If you want to query all users that have allowed set to true, use:

const allowedUsers = await db.query('users').filter('allowed', '==', true).get();

Kindly note that instead of rolling your own auth, you might want to use AceBase server's built-in auth. See https://github.com/appy-one/acebase-server and https://github.com/appy-one/acebase-client

Do you like AceBase? 👇🏼

Sponsor AceBase Spread the word contribute