DEV Community

Cover image for step by step crud operation in motoko - how to store and retrieve data

step by step crud operation in motoko - how to store and retrieve data

To store 1 question and 4 options in Motoko efficiently, you should define a structured Record type to hold the data, rather than a raw Buffer. If you need to store multiple of these questions in a resizable container, you would use a Buffer to hold those records.

Here is the recommended implementation using an Actor to manage the question storage.

  1. Define the TypesUse a stable Record type to ensure the data persists across upgrades.
motoko

type Option = Text;
type Question = {
    questionText : Text;
    options : [Option]; // Array of 4 options
    correctOptionIndex : Nat; // Index 0-3
};

Enter fullscreen mode Exit fullscreen mode
  1. Implementation Using BufferThis actor initializes with a Buffer to store multiple Question records.
motoko

import Buffer "mo:base/Buffer";
import Array "mo:base/Array";

actor QuestionManager {

    // Define the type for the question
    public type Question = {
        questionText : Text;
        options : [Text]; // Expected size 4
        correctOptionIndex : Nat; // 0, 1, 2, or 3
    };

    // Buffer is a resizable array
    let questionsBuffer = Buffer.Buffer<Question>(10);

    // Function to add a question
    public func addQuestion(q : Question) : async () {
        // Simple validation: Ensure 4 options
        if (q.options.size() == 4) {
            questionsBuffer.add(q);
        };
    };

    // Function to get all questions
    public query func getQuestions() : async [Question] {
        // Convert buffer to immutable array for returning
        return questionsBuffer.toArray();
    };

    // Function to get total question count
    public query func getCount() : async Nat {
        return questionsBuffer.size(); //
    };
}

Enter fullscreen mode Exit fullscreen mode

Key Motoko Concepts

  • Used[Records]: { questionText : Text; ... } defines a structured object.

  • [Buffer]: Buffer.Buffer(10) creates a mutable, resizable container, ideal for managing lists of data on the heap.

  • [Array]: [Text] is a fixed-size array, perfect for the 4 options, ensuring they are immutable and easily shared.

  • ToArray: questionsBuffer.toArray() converts the mutable buffer into a shared, immutable array format required for canister return values.

Run and test

# Starts the replica, running in the background
dfx start --background

# Deploys your canisters to the replica and generates your candid interface. It basically deploys the fullstack application

dfx deploy
Enter fullscreen mode Exit fullscreen mode

Read more...
Motoko Book
Mops Docs

Top comments (0)