Tutorial: Use MiniMongo with Next.js

How to Use Minimongo with Next.js

Minimongo is a small, in-memory MongoDB-like database that's often used in Meteor.js applications.

While Next.js doesn't natively support Minimongo, you can still integrate it into your Next.js project to create a simple and lightweight in-memory database.

Set Up a Next.js Project

First, ensure you have Node.js and npm installed. If not, download and install them from Node.js.

Start the development server:

npm run dev

Create a new Next.js project:

npx create-next-app@latest nextjs-minimongo
cd nextjs-minimongo

Install Minimongo

Minimongo can be installed using npm:

npm install minimongo

Create a Minimongo Database

Now let's create a simple Minimongo database and use it in a Next.js page.

Open index.js and add the following code to set up a Minimongo database and insert some data:

import React, { useEffect, useState } from 'react';
import LocalDb from 'minimongo';

export default function Home() {
    const [todos, setTodos] = useState([]);

    useEffect(() => {
        // Initialize Minimongo
        const db = new LocalDb();

        // Create a collection
        db.addCollection('todos');

        // Insert some initial data
        db.todos.upsert({ _id: '1', text: 'Learn Next.js' });
        db.todos.upsert({ _id: '2', text: 'Integrate Minimongo' });

        // Query data from the collection
        db.todos.find().fetch((err, results) => {
            setTodos(results);
        });
    }, []);

    return (
        <div>
            <h1>My Todo List</h1>
            <ul>
                {todos.map((todo) => (
                    <li key={todo._id}>{todo.text}</li>
                ))}
            </ul>
        </div>
    );
}

Inside the pages directory, create a new file named index.js:

touch pages/index.js

Run Your Application

Now, run your application using:

npm run dev

You should see a simple list of todos displayed on the homepage.

Explanation

  • LocalDb: Minimongo is initialized with LocalDb, which creates an in-memory database.
  • addCollection: This method creates a new collection named todos.
  • upsert: This method inserts or updates documents in the collection.
  • find: This method queries the collection, and fetch retrieves the results.

Advanced Usage (Optional)

If you want to persist the Minimongo data between page reloads, you can use localStorage to save and load the data.

Update the useEffect hook to include loading and saving the data:

useEffect(() => {
    const db = new LocalDb();

    db.addCollection('todos');

    // Load data from localStorage
    const savedTodos = localStorage.getItem('todos');
    if (savedTodos) {
        db.todos.upsert(JSON.parse(savedTodos));
    } else {
        db.todos.upsert({ _id: '1', text: 'Learn Next.js' });
        db.todos.upsert({ _id: '2', text: 'Integrate Minimongo' });
    }

    db.todos.find().fetch((err, results) => {
        setTodos(results);
    });

    // Save data to localStorage on change
    db.todos.find().observe({
        added: () => {
            localStorage.setItem('todos', JSON.stringify(db.todos._data));
        },
        changed: () => {
            localStorage.setItem('todos', JSON.stringify(db.todos._data));
        },
    });
}, []);

Conclusion

Minimongo can be a useful tool for small-scale, in-memory databases in a Next.js project. While it’s more commonly used in Meteor.js, it can be adapted for use with Next.js for lightweight applications or rapid prototyping.

This tutorial provided a basic integration, but you can expand upon it by adding more collections, implementing updates, or even syncing with a server-side database.








Open-source Apps

9,500+

Medical Apps

500+

Lists

450+

Dev. Resources

900+

Read more