npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongo-validate

v0.0.1

Published

Lightweight schema validation for MongoDB with Zod

Downloads

2

Readme

Mongo Validate

Stronger, more intuitive type checking and assertions for MongoDB.

Mongo Validate extends the functionality of Zod, integrated with the MongoDB Node.js driver, to provide a more intuitive and powerful way to validate MongoDB documents.

Some of its features include:

  • Validation of unique fields
  • Validation of the integrity of references to other collections
  • Adherence to a Zod schema

But why?

Mongo Validate is something I put together out of frustration with existing, heavy handed solutions for MongoDB schema management. Mongo Validate is intended to have a minimal footprint, add on to existing validation infrastructure, and plug in seamlessly to build-time integrity checks.

Usage

Mongo Validate is available as an NPM package. To install it, run:

npm install mongo-validate
pnpm install mongo-validate
yarn add mongo-validate
bun install mongo-validate

Mongo Validate supports Zod schemas out of the box, so any schemas you may already have defined can be used with any MongoDB instance.

Examples

Getting started

For all of the examples below, we'll be using the following schema:

import { z } from 'zod';
import { ObjectId } from "mongo-validate/lib/mongodb"

export const userSchema = z.object({
    _id: ObjectId,
    name: z.string(),
    email: z.string().email(),
});

export type User = z.infer<typeof userSchema>;

Unique field validation

Mongo Validate extends Zod schemas to check that your documents match the desired schema. For example:

import mongo-validate, { type AssertUniqueType } from 'mongo-validate';
import { userSchema, type User } from "./schemas";

export const UserEmailsUniqueValidator = MongoValidate.assertUnique.fromSchema(userSchema, ["email"]);
//               ^? AssertUniqueType<User>

The returned object is a Zod schema that can be directly invoked to validate a result from MongoDB. This object is of the type:

type AssertUniqueType<T> = z.ZodEffects<z.ZodArray<z.ZodType<T>>, T[], unknown>;

And you can use it like this:

import { createMongoClient } from "./your-mongo-client";
import { UserEmailsUniqueValidator } from "./schemas";

const client = await createMongoClient(url, options);

async function main() {
    const users: WithId<Document>[] = await client.db("db").collection("users").find().toArray();

    try {
        return UserEmailsUniqueValidator.parse(users) satisfies User[];
    } catch (e) {
        console.error(e);
        return;
    }
}

Reference validation

Mongo Validate also supports validation of references to other collections.

For example, suppose we have a collection of Stores that must be associated to an existing User. Let's define our schema first:

import { z } from 'zod';

export const storeSchema = z.object({
    _id: ObjectId,
    name: z.string(),
    owner: z.string(),
    ownerEmail: z.string().email(),
});

export type Store = z.infer<typeof storeSchema>;

Now, we can define a reference validator between these two collections:

import mongo-validate from 'mongo-validate';

const StoresHaveOwnersValidator = new MongoValidate.assertRelation({
    db: "your-db",
    mainCollection: "users",
    relationCollection: "stores",
    mainSchema: userSchema,
    relationSchema: storeSchema,
    relations: {
        "email": "ownerEmail"
    }
});

And then we can use it like this:

import { createMongoClient } from "./your-mongo-client";
import { StoresHaveOwnersValidator } from "./schemas";

const client = await createMongoClient(url, options);

async function main() {
    const stores: WithId<Document>[] = await client.db("db").collection("stores").find().toArray();

    try {
        return StoresHaveOwnersValidator.parse(stores) satisfies Store[];
    } catch (e) {
        console.error(e);
        return;
    }
}