Home > database >  FireStore(NoSQL) fetching limited in nested data
FireStore(NoSQL) fetching limited in nested data

Time:03-29

Currently, I working on personal project. I want to build a test online.

I'm using Firestore(NoSQL) for storing Test and Question

This is my current schema

{
  "id": "Test ID",
  "name": "Test Name",
  "number_of_question": 20, // Number of question will fetch from question_bank
  "question_bank": [
      {"id": "Question ID",
        "name": "Question Name 1 ?",
        "answer": ["A","B","C","D"],
        "correct_answer": ["A","B"]
      },
      {
        "id": "Question ID 2",
        "name": "Question Name 2 ?",
        "answer": ["A","B","C","D"],
        "correct_answer": ["A"]
      }, ...
    ]
}

Because in the future, there are possibility that the question_bank become very large (1000 questions)

Is there a way or a better schema that we can tell NoSQL to fetch (randomly limited to number_of_question)questions in question_banks. (I really want to hit the database only 1 for this action)

CodePudding user response:

Firestore will always return the whole document so you cannot fetch just a few items from that array. The question_bank can be a sub-collection where each question in question_bank array is a document. Then you can specify number of documents to query from the sub-collection.

const snap = await db.collection('quizzes/{quizId}/questions').limit(20).get()
// can add more query clauses if required

If you want to fetch random documents from that sub-collection, checkout:

Firestore: How to get random documents in a collection

CodePudding user response:

It sounds like you'll want to use a subcollection for the question_bank of each test. With a subcollection you can query the questions for a specific test, retrieving a subset of them.

I recommend checking out the Firebase documentation on the hierarchical data model of Firestore, and on performing queries.

  • Related