memongo is a lightweight, ZERO-dependency, in-memory document database with pluggable persistence.
npm install memongo
All examples in this repository are written in TypeScript, but they work in JavaScript without any change.
import { createDatabase } from "memongo";
async function main() {
// 1) Create an in-memory database (no persistence argument).
const db = createDatabase();
await db.init();
// 2) Create or get a collection.
let todos = db.collection("todos");
if (!todos) {
todos = db.createCollection("todos");
}
// 3) Add documents.
const { _id: drinkMilkId } = todos.add({
title: "Drink milk in the morning",
done: false,
priority: 0,
});
todos.add({
title: "Eat snacks in the afternoon",
done: false,
priority: 2,
});
todos.add({
title: "Read memongo examples",
done: false,
priority: 1,
});
todos.add({
title: "Use memongo in my project and add learning tests",
done: false,
priority: 1,
});
console.log("\nAfter add:", todos.get());
// 4) Get single document.
const drinkMilk = todos.doc(drinkMilkId).get();
console.log("\nThe Drink milk todo:", drinkMilk);
// 5) Update single document.
todos.doc(drinkMilkId).update({
done: true,
});
console.log("\nAfter marking drink milk as done:", todos.get());
// 6) Get documents that satisfy the condition.
const doneTodos = todos.where({ done: true }).get();
console.log("\nDone todos:", doneTodos);
// 7) Remove single document.
todos.doc(drinkMilkId).remove();
console.log("\nAfter removing the done Drink milk todo:", todos.get());
// 8) Update documents that satisfy the condition.
todos.where({ done: false, priority: 1 }).update({ done: true });
console.log("\nAfter marking todos with priority 1 as done:", todos.get());
// 9) Remove documents that satisfy the condition.
todos.where({ done: true }).remove();
console.log("\nAfter removing done todos:", todos.get());
// 10) Remove all documents in the collection.
todos.remove();
console.log("\nAfter clearing the todo collection:", todos.get());
}
main();
Write operations apply changes to the in-memory state synchronously.
If persistence is configured, data is automatically written asynchronously in the background.
To ensure all pending persistence operations are completed (which is usually not needed), call:
await db.flush();
Persistence-related errors are not thrown during write operations. They are reported when calling flush().
See this example for detailed usage.
Usage Examples:
See examples
importThanks to the following open-source projects: