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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@cbnsndwch/zero-nest-mongoose

v0.6.0

Published

Automatic Zero schema generation from NestJS Mongoose schemas with full TypeScript support. Seamlessly convert your existing Mongoose models into Rocicorp Zero schemas with type-safe table definitions, relationships, and virtual tables.

Readme

@cbnsndwch/zero-nest-mongoose

Automatic Zero schema generation from NestJS Mongoose schemas

npm version License: MIT

Overview

@cbnsndwch/zero-nest-mongoose automatically generates Rocicorp Zero schemas from your existing NestJS Mongoose schemas. This eliminates manual schema duplication and keeps your MongoDB models and Zero schemas perfectly synchronized with full TypeScript support.

Features

  • 🔄 Automatic Schema Generation: Convert Mongoose schemas to Zero schemas automatically
  • 🎯 Type Safety: Full TypeScript support with proper type inference
  • 📊 Relationship Mapping: Automatic detection and mapping of schema relationships
  • 🏗️ Virtual Tables: Support for Zero virtual tables and discriminated unions
  • 🔌 NestJS Integration: Seamless integration with NestJS dependency injection
  • Zero Config: Works out of the box with minimal configuration
  • 🛠️ Customizable: Override and customize generated schemas as needed

Installation

pnpm add @cbnsndwch/zero-nest-mongoose

Peer Dependencies:

{
    "@nestjs/common": "^11",
    "@nestjs/mongoose": "^11",
    "@rocicorp/zero": "0.24.3000000000",
    "mongoose": "^8.9.5"
}

Quick Start

1. Define Your Mongoose Schema

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';

@Schema({ timestamps: true })
export class User extends Document {
    @Prop({ required: true })
    name: string;

    @Prop({ required: true, unique: true })
    email: string;

    @Prop({ type: Types.ObjectId, ref: 'Organization' })
    organizationId: Types.ObjectId;

    @Prop({ default: Date.now })
    createdAt: Date;
}

export const UserSchema = SchemaFactory.createForClass(User);

2. Generate Zero Schema

import { generateZeroSchema } from '@cbnsndwch/zero-nest-mongoose';

// Automatically generate Zero schema from Mongoose schema
const userTable = generateZeroSchema(UserSchema, 'users');

console.log(userTable);
// Output:
// {
//   tableName: 'users',
//   columns: {
//     id: { type: 'string' },
//     name: { type: 'string' },
//     email: { type: 'string' },
//     organizationId: { type: 'string' },
//     createdAt: { type: 'number' }
//   },
//   primaryKey: ['id'],
//   relationships: {
//     organization: {
//       sourceField: ['organizationId'],
//       destSchema: () => organizationTable,
//       destField: ['id']
//     }
//   }
// }

3. Use in Your Zero Client

import { Zero } from '@rocicorp/zero';
import { createSchema } from '@rocicorp/zero';

const schema = createSchema({
    version: 1,
    tables: {
        users: userTable
        // ... other tables
    }
});

const zero = new Zero({
    server: 'ws://localhost:4848',
    schema,
    userID: 'user-123'
});

Advanced Usage

Multiple Schemas

import { generateZeroSchemas } from '@cbnsndwch/zero-nest-mongoose';

// Generate schemas for all your models at once
const schemas = generateZeroSchemas({
    users: UserSchema,
    posts: PostSchema,
    comments: CommentSchema
});

const zeroSchema = createSchema({
    version: 1,
    tables: schemas
});

Custom Field Mapping

import { generateZeroSchema, FieldMapper } from '@cbnsndwch/zero-nest-mongoose';

const customMapper: FieldMapper = {
    // Map MongoDB types to Zero types
    ObjectId: 'string',
    Date: 'number',
    Mixed: 'json'
};

const userTable = generateZeroSchema(UserSchema, 'users', {
    fieldMapper: customMapper
});

Relationship Configuration

import { generateZeroSchema } from '@cbnsndwch/zero-nest-mongoose';

const userTable = generateZeroSchema(UserSchema, 'users', {
    relationships: {
        // Override auto-detected relationships
        organization: {
            sourceField: ['organizationId'],
            destTable: 'organizations',
            destField: ['id']
        }
    }
});

Virtual Tables

import { generateZeroSchema } from '@cbnsndwch/zero-nest-mongoose';

// Generate multiple Zero tables from single Mongoose schema
const roomSchemas = generateZeroSchema(RoomSchema, 'rooms', {
    virtualTables: [
        {
            tableName: 'chats',
            discriminator: { field: 'type', value: 'chat' }
        },
        {
            tableName: 'channels',
            discriminator: { field: 'type', value: 'channel' }
        },
        {
            tableName: 'groups',
            discriminator: { field: 'type', value: 'group' }
        }
    ]
});

// Returns: { chats: {...}, channels: {...}, groups: {...} }

Excluding Fields

const userTable = generateZeroSchema(UserSchema, 'users', {
    exclude: ['password', '__v', 'passwordResetToken']
});

Custom Primary Key

const userTable = generateZeroSchema(UserSchema, 'users', {
    primaryKey: ['email'] // Use email instead of _id
});

Type Mapping

The library automatically maps Mongoose types to Zero types:

| Mongoose Type | Zero Type | | ------------- | --------- | | String | string | | Number | number | | Boolean | boolean | | Date | number | | ObjectId | string | | Buffer | string | | Mixed | json | | Array | json |

API Reference

generateZeroSchema(schema, tableName, options?)

Generates a Zero table schema from a Mongoose schema.

Parameters:

  • schema: Schema - Mongoose schema
  • tableName: string - Name for the Zero table
  • options?: GenerateOptions - Optional configuration

Returns: TableSchema - Zero table schema definition

generateZeroSchemas(schemas, options?)

Generates multiple Zero table schemas at once.

Parameters:

  • schemas: Record<string, Schema> - Map of table names to Mongoose schemas
  • options?: GenerateOptions - Optional configuration

Returns: Record<string, TableSchema> - Map of Zero table schemas

GenerateOptions

interface GenerateOptions {
    // Custom field type mapping
    fieldMapper?: FieldMapper;

    // Override relationship detection
    relationships?: Record<string, RelationshipConfig>;

    // Fields to exclude from schema
    exclude?: string[];

    // Custom primary key
    primaryKey?: string[];

    // Generate virtual tables
    virtualTables?: VirtualTableConfig[];
}

Integration Patterns

With NestJS Module

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { generateZeroSchema } from '@cbnsndwch/zero-nest-mongoose';
import { User, UserSchema } from './entities/user.entity';

@Module({
    imports: [
        MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])
    ],
    providers: [
        {
            provide: 'ZERO_USER_SCHEMA',
            useFactory: () => generateZeroSchema(UserSchema, 'users')
        }
    ],
    exports: ['ZERO_USER_SCHEMA']
})
export class UsersModule {}

Schema Export Endpoint

import { Controller, Get } from '@nestjs/common';
import { generateZeroSchemas } from '@cbnsndwch/zero-nest-mongoose';

@Controller('api/schema')
export class SchemaController {
    @Get('export')
    exportSchema() {
        const schemas = generateZeroSchemas({
            users: UserSchema,
            posts: PostSchema,
            comments: CommentSchema
        });

        return {
            version: 1,
            tables: schemas
        };
    }
}

Examples

Complete Example

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Zero } from '@rocicorp/zero';
import { generateZeroSchemas } from '@cbnsndwch/zero-nest-mongoose';
import { UserSchema } from './entities/user.entity';
import { PostSchema } from './entities/post.entity';

// Generate schemas
const tables = generateZeroSchemas({
    users: UserSchema,
    posts: PostSchema
});

// Create Zero schema
const schema = createSchema({
    version: 1,
    tables
});

// Initialize Zero client
const zero = new Zero({
    server: 'ws://localhost:4848',
    schema,
    userID: 'user-123'
});

// Query data with Zero
const users = await zero.query.users
    .where('organizationId', '=', 'org-123')
    .run();

Best Practices

  1. Generate Once: Generate schemas at build time or application startup
  2. Version Control: Keep generated schemas in version control for review
  3. Type Safety: Use TypeScript for full type checking
  4. Relationship Validation: Verify auto-detected relationships match your data model
  5. Testing: Test generated schemas with sample data

Troubleshooting

Schema Not Generated Correctly

// Enable debug logging
const schema = generateZeroSchema(UserSchema, 'users', {
    debug: true // Logs schema generation process
});

Relationship Detection Issues

// Manually specify relationships
const schema = generateZeroSchema(UserSchema, 'users', {
    relationships: {
        organization: {
            sourceField: ['organizationId'],
            destTable: 'organizations',
            destField: ['id']
        }
    }
});

Development

# Install dependencies
pnpm install

# Build the package
pnpm build

# Run tests
pnpm test

# Lint code
pnpm lint

Contributing

Contributions are welcome! Please see the main repository for contribution guidelines.

License

MIT © cbnsndwch LLC

Related Packages

Resources