惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
GbyAI
GbyAI
人人都是产品经理
人人都是产品经理
T
Tor Project blog
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
爱范儿
爱范儿
雷峰网
雷峰网
MongoDB | Blog
MongoDB | Blog
Vercel News
Vercel News
美团技术团队
博客园 - 三生石上(FineUI控件)
D
DataBreaches.Net
L
LangChain Blog
IT之家
IT之家
博客园_首页
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
T
Tailwind CSS Blog
M
MIT News - Artificial intelligence
P
Proofpoint News Feed
Hacker News: Ask HN
Hacker News: Ask HN
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位
Project Zero
Project Zero
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东
T
Tenable Blog
aimingoo的专栏
aimingoo的专栏
P
Proofpoint News Feed
T
Threat Research - Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
Microsoft Azure Blog
Microsoft Azure Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 叶小钗
Know Your Adversary
Know Your Adversary
L
Lohrmann on Cybersecurity
C
Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Schneier on Security
Schneier on Security
I
InfoQ
P
Privacy & Cybersecurity Law Blog
Spread Privacy
Spread Privacy
Martin Fowler
Martin Fowler
腾讯CDC
S
Security @ Cisco Blogs
F
Fortinet All Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
MongoDB Schema Validation: How JSON Schema Keeps Your Data Clean
Roxana-Maria Haidiner · 2026-06-03 · via DEV Community

The "schemaless" database has had JSON Schema validation since 2017. Here's what you're missing.


"MongoDB is schemaless."

"MongoDB is unorganized."

"MongoDB lets you store anything, so your data becomes a mess."

These are common misconceptions, but they're only true if you choose to work that way.

Since MongoDB 3.6, the database has had built-in schema validation using JSON Schema. You can enforce field types, required fields, value constraints, and nested object structures at the database level. Documents that don't match get rejected before they're ever written.

MongoDB gives you both worlds: flexibility when you need it, structure when you want it. The choice has always been yours.


The Misconception

The "schemaless" label comes from MongoDB's default behavior: it accepts any document structure without complaint. You can insert { name: "Alice" } followed by { firstName: "Bob", age: 30 } into the same collection. No errors.

For prototyping and exploration, this flexibility is invaluable. For production systems, you might want more guardrails.

MongoDB gives you both options. Since version 3.6, you can define validation rules using $jsonSchema — and the database enforces them on every insert and update. Use the flexibility when you need it, add structure when you're ready.


What is JSON Schema?

JSON Schema is a standard for describing the structure of JSON documents. It's not MongoDB-specific — it's used across the industry for API validation, configuration files, and data contracts.

MongoDB implements JSON Schema Draft 4 with some BSON-specific extensions. You define what fields are required, what types they should be, and what constraints apply. The database does the rest.


Basic Schema Validation

Here's how you create a collection with validation:

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["email", "createdAt"],
      properties: {
        email: {
          bsonType: "string",
          pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
          description: "Must be a valid email address"
        },
        name: {
          bsonType: "string",
          minLength: 1,
          maxLength: 100
        },
        age: {
          bsonType: "int",
          minimum: 0,
          maximum: 150
        },
        role: {
          enum: ["admin", "user", "viewer"],
          description: "Must be one of the allowed roles"
        },
        createdAt: {
          bsonType: "date"
        }
      }
    }
  },
  validationLevel: "strict",
  validationAction: "error"
})

Enter fullscreen mode Exit fullscreen mode

Now try to insert an invalid document:

db.users.insertOne({ email: "not-an-email", name: "Alice" })
// Error: Document failed validation

Enter fullscreen mode Exit fullscreen mode

The database rejected it. No application code needed.


JSON Schema Features

Required Fields

required: ["email", "createdAt", "status"]

Enter fullscreen mode Exit fullscreen mode

Documents missing any of these fields are rejected.

BSON Types

MongoDB extends JSON Schema with bsonType for MongoDB-specific types:

bsonType Description
"string" Text
"int" 32-bit integer
"long" 64-bit integer
"double" Floating point
"decimal" 128-bit decimal (financial precision)
"bool" Boolean (note: not "boolean")
"date" Date object
"objectId" MongoDB ObjectId
"array" Array
"object" Nested document
"null" Null value
"binData" Binary data

Validation Options

validationLevel

  • "strict" — Validate all inserts and updates (default)
  • "moderate" — Only validate documents that already match the schema; allows existing invalid documents to be updated

validationAction

  • "error" — Reject invalid documents (default)
  • "warn" — Allow invalid documents but log a warning

For gradual adoption, start with validationAction: "warn" to see what would fail, then switch to "error" once you've cleaned up existing data.


Common Mistakes

1. Using "boolean" instead of "bool"

// Wrong
isActive: { bsonType: "boolean" }

// Correct
isActive: { bsonType: "bool" }

Enter fullscreen mode Exit fullscreen mode

2. Mixing type and bsonType

// Wrong — can't use both
email: { type: "string", bsonType: "string" }

// Correct — use bsonType for MongoDB
email: { bsonType: "string" }

Enter fullscreen mode Exit fullscreen mode

3. Forgetting that additionalProperties defaults to true

By default, MongoDB allows fields not defined in your schema. To reject unknown fields:

{
  bsonType: "object",
  properties: { /* ... */ },
  additionalProperties: false
}

Enter fullscreen mode Exit fullscreen mode

JSON Schema Validation

How VisuaLeaf Handles Schema Validation Visually

Writing JSON Schema by hand works, but it's tedious for complex schemas. Visualeaf provides a visual schema designer that makes it intuitive.

Auto-Generate from Collection

Starting from scratch? Visualeaf can analyze an existing collection and generate a schema based on the actual documents. It detects:

  • Field names and types
  • Which fields appear in all documents (candidates for required)
  • Nested object structures
  • Array item types

Use it as a starting point, then refine.

Tree-Based Schema Editor

Instead of writing JSON, you build schemas visually:

  • Expandable tree structure — See your schema hierarchy at a glance
  • Inline field editing — Click to rename fields
  • Type dropdowns — Select bsonType from a list (string, number, date, objectId, array, object, etc.)
  • Required checkboxes — Toggle required fields with one click
  • Add/delete/duplicate — Modify structure without editing JSON

Split-Panel Layout

The editor shows two synchronized views:

  • Left panel — Interactive tree editor
  • Right panel — Live JSON Schema preview with syntax highlighting

Edit in the tree, see the JSON update in real-time. Or edit the JSON directly if you prefer.

Type-Specific Constraint Panels

When you select a field, Visualeaf shows relevant constraints for that type:

  • String: minLength, maxLength, pattern (regex), enum values
  • Number: minimum, maximum, multipleOf, exclusiveMin/Max
  • Array: minItems, maxItems, uniqueItems, item type
  • Object: required fields, nested properties, additionalProperties

No memorizing which constraints apply to which types — the UI shows only what's relevant.

Schema Verification

Before applying a schema, you may want to know: will my existing data pass?

Visualeaf's Verify Schema feature runs your schema against a collection and shows:

  • How many documents pass
  • How many documents fail
  • Which specific documents fail and why

Fix your data or adjust your schema before enforcement.

One-Click Application

Once your schema is ready:

  1. Click Apply Schema
  2. Select target collection
  3. Choose validation level (strict/moderate) and action (error/warn)
  4. Done — schema is now enforced at the database level

No db.runCommand() syntax to remember. No copy-pasting JSON into the shell.


The Bottom Line

MongoDB isn't schemaless unless you want it to be.

$jsonSchema validation has been available since 2017. It enforces structure at the database level — no ORM needed, no application code required. Documents that don't match get rejected before they're stored.

Want strict schemas? MongoDB supports that. Need flexibility for rapid prototyping or evolving data? That's there too. The choice is yours.

That's the real power of MongoDB: it doesn't force you into one approach. Use schemas when structure matters. Skip them when flexibility matters more. The database adapts to your needs, not the other way around.


Visualeaf makes MongoDB schema validation visual. Design schemas with a tree editor, verify against live data, and apply with one click — no JSON syntax required.

How VisuaLeaf Handles Schema Validation Visually

Writing JSON Schema by hand works, but it's tedious for complex schemas. Visualeaf provides a visual schema designer that makes it intuitive.

Auto-Generate from Collection

Starting from scratch? Visualeaf can analyze an existing collection and generate a schema based on the actual documents. It detects:

  • Field names and types
  • Which fields appear in all documents (candidates for required)
  • Nested object structures
  • Array item types

Use it as a starting point, then refine.

Tree-Based Schema Editor

Instead of writing JSON, you build schemas visually:

  • Expandable tree structure — See your schema hierarchy at a glance
  • Inline field editing — Click to rename fields
  • Type dropdowns — Select bsonType from a list (string, number, date, objectId, array, object, etc.)
  • Required checkboxes — Toggle required fields with one click
  • Add/delete/duplicate — Modify structure without editing JSON

Split-Panel Layout

The editor shows two synchronized views:

  • Left panel — Interactive tree editor
  • Right panel — Live JSON Schema preview with syntax highlighting

Edit in the tree, see the JSON update in real-time. Or edit the JSON directly if you prefer.

Type-Specific Constraint Panels

When you select a field, Visualeaf shows relevant constraints for that type:

  • String: minLength, maxLength, pattern (regex), enum values
  • Number: minimum, maximum, multipleOf, exclusiveMin/Max
  • Array: minItems, maxItems, uniqueItems, item type
  • Object: required fields, nested properties, additionalProperties

No memorizing which constraints apply to which types — the UI shows only what's relevant.

Edit the validation before apply it.

Schema Verification

Before applying a schema, you may want to know: will my existing data pass?

Visualeaf's Verify Schema feature runs your schema against a collection and shows:

  • How many documents pass
  • How many documents fail
  • Which specific documents fail and why

Fix your data or adjust your schema before enforcement.

One-Click Application

Once your schema is ready:

  1. Click Apply Schema
  2. Select target collection
  3. Choose validation level (strict/moderate) and action (error/warn)
  4. Done — schema is now enforced at the database level

No db.runCommand() syntax to remember. No copy-pasting JSON into the shell.


Apply the schema as $jsonSchema Validator

The Bottom Line

MongoDB isn't schemaless unless you want it to be.

$jsonSchema validation has been available since 2017. It enforces structure at the database level — no ORM needed, no application code required. Documents that don't match get rejected before they're stored.

Want strict schemas? MongoDB supports that. Need flexibility for rapid prototyping or evolving data? That's there too. The choice is yours.

That's the real power of MongoDB: it doesn't force you into one approach. Use schemas when structure matters. Skip them when flexibility matters more. The database adapts to your needs, not the other way around.


Visualeaf makes MongoDB schema validation visual. Design schemas with a tree editor, verify against live data, and apply with one click — no JSON syntax required.


Sources