简体   繁体   中英

How to correctly query a Firebase Realtime Database Flutter?

Im really new to firebase realtime databases and i didnt have time to learn it thoroughly before starting a school project. The queries are not working properly.

I have a database that looks like the following:

{
  "cat": {
    "-NKKUp_AiD98WHUvnfR0": {
      "birthYear": "2001",
      "imageUrl": "***",
      "name": "Tom"
    }
  },
  "user": {
    "uFkR1Z1UoVTVUmbpDmgU7BXGT852": {
      "admin": true,
      "email": "ziaddddd@gmail.com",
      "fullName": "ziad212",
      "phoneNo": "011111111"
    }
  }
}

I want to create a new node 'request' and set its children to the current uId, the cat name, and the userName. but im having trouble with the user name. Here is my code:

static requestCat(catName) async {
    final uId = AuthenticationRepository.auth.currentUser!.uid;
    Query query = DbHelper.database.ref('user').orderByValue().equalTo(uId);

    final snapshot = await query.get();
    final user = snapshot.value as Map;

    user['key'] = snapshot.key;
    var userName = user['fullName'];
    DatabaseReference ref = DbHelper.database.ref('request');

    ref.push().set(
      {'catName': catName, 
      'userName': userName, 
      'userId': uId
      }
    );
  }
}

It gives me the following error when i call the funtion:

Error: [firebase_database/index-not-defined] Index not defined, add ".indexOn": ".value", for path "/user", to the rules
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49  throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 49:5
_startMicrotaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15           <fn>

What am i doing wrong?

As the error says, you need to add an index to your database to allow this query. You can do this in the security rules of your database, typically in the Firebase console . For this specific query, the rules would be:

{
  "rules": {
    ...
    "user": {
      ".indexOn": ".value";
    }
  }
}

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