MongoDB Access Layer.
Mongalayer is a type-safe abstraction layer between your MongoDB database and TypeScript clients, designed for basic CRUD applications. Define schemas with Zod, control access through role-based definitions, and query your data with full type safety — from server to client.
<script setup lang="ts">
import { Project } from "model/project";
const { $database } = useNuxtApp();
const allProjects: Ref<Project[]> = ref([]);
onMounted(async () => {
allProjects.value = await $database.collection<Project>("projects").find();
});
</script>
import { MongalayerClient } from "@mongalayer/client";
export default defineNuxtPlugin(async nuxtApp => {
const client = new MongalayerClient("https://...", {
headers: async () => {
const session = await getSession(); // Dummy function
return { Authorization: session.token };
}
});
const database = client.db("myDatabase");
return {
provide: {
database
}
}
})
import z from "zod";
export class Project {
constructor(
public _id: string,
public name: string,
public description: string,
public ownerId: string,
public createdAt: Date,
) { }
static schema = z.strictObject({
_id: z.string(),
name: z.string(),
description: z.string(),
ownerId: z.string(),
createdAt: z.date()
});
}
import { AccessPermissions } from "@mongalayer/server";
import type { AccessConfig } from "@mongalayer/server";
import type { Project } from "model/project";
const projectAccess: AccessConfig<Project> = [{
role: "owner",
filter: {
ownerId: "%%user.id"
},
document: AccessPermissions.ReadWrite,
fields: {
// CreatedAt is read-only after creation
createdAt: AccessPermissions.ReadWrite ^ AccessPermissions.Update
},
delete: true
}, {
role: "user",
filter: {}, // Public
document: AccessPermissions.Read
}];
Key Features
Role-Based Access Control
Define granular access roles with document-level and field-level permissions. Control who can read, create, update, and delete data.
Schema Validation
Define your document schemas with Zod. All payloads are validated automatically before reaching MongoDB.
Full Type Safety
End-to-end TypeScript types from server to client. Actions, payloads, and return types are all fully typed.
MongoDB CRUD Operations
Supports find, findOne, findOneAndUpdate, aggregate, insertOne, insertMany, updateOne, updateMany, deleteOne, and deleteMany from your client code.
Client SDK
A lightweight client library that communicates with the Mongalayer server over HTTP. Works in any JavaScript environment with fetch.
Bring Your Own Auth
Authentication and authorization of HTTP requests is handled by you. Mongalayer focuses on data access control, not transport security.