Fetching latest headlines…
step by step crud operation in motoko - how to store and retrieve data
NORTH AMERICA
🇺🇸 United StatesMay 9, 2026

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

0 views0 likes0 comments
Originally published byDev.to

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
};

  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(); //
    };
}

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.

Read more...
Motoko Book
Mops Docs

Comments (0)

Sign in to join the discussion

Be the first to comment!