JSON to Mongoose Schema

Generate Mongoose schemas from JSON instantly. Supports JavaScript and TypeScript output, timestamps option, nested objects, and arrays. Free, runs in your browser.

  • Runs in your browser
  • Tool input is not uploaded to ZeroTool servers
  • Free · No Sign-Up
Name the model and root schema. A blank name uses User. Simple names such as User or Order are recommended.
Language JavaScript uses CommonJS require and module.exports. TypeScript uses import/export and document interfaces passed to Schema and model.
timestamps On adds timestamps: true to the root schema. TypeScript also includes createdAt and updatedAt as Date unless those keys already exist in the JSON.
required On adds required: true to primitive, date, mixed and primitive-array fields. Nested schemas and arrays of objects keep their existing form.
Replace the JSON with a user document containing nested objects and arrays, then generate with the current model name and options.
Clear JSON, output and status. Keep the model name and options. Ctrl/⌘+L in this tool also clears the model name.
Enter valid JSON. Input and model-name edits generate after 300 ms; the three option groups update immediately. Invalid JSON clears the output and disables Copy.
Mongoose Schema Output
Copy the complete displayed schema and model export. Copy is disabled when the output is empty.

Enter JSON or load the example to generate a Mongoose schema.

Examples, details and FAQ Worked examples, how it compares with other tools, and answers to common questions.

Type Mapping

  • null fits any type and is skipped; a field that is null in every sample → mongoose.Schema.Types.Mixed
  • a field whose samples have different types (number and string, object and string) → mongoose.Schema.Types.Mixed; ISO date-times mixed with other strings → String
  • string that starts like an ISO 8601 date-time (2026-10-01T09:30:00Z) → Date; a plain date such as 2026-10-01, a date-time with a space instead of T (2026-10-01 09:30:00) and date-times inside an array stay String
  • string → String
  • number → Number
  • boolean → Boolean
  • array of primitives → [String] / [Number] / [Boolean]
  • array of objects → [subSchema] (separate schema generated)
  • nested object → separate schema variable referenced inline

Example

Given this JSON with model name User:

{"username": "alice", "age": 28, "tags": ["admin"], "address": {"city": "London"}}

JavaScript output (timestamps On):

const mongoose = require('mongoose');
const { Schema } = mongoose;

const addressSchema = new Schema({
  city: { type: String },
});

const userSchema = new Schema({
  username: { type: String },
  age: { type: Number },
  tags: [String],
  address: addressSchema,
}, { timestamps: true });

module.exports = mongoose.model('User', userSchema);

Sub-schemas are named after the key (address → addressSchema) and written before the schema that uses them, so the file runs top to bottom. The model name is converted to PascalCase for mongoose.model(); Mongoose then derives the collection name by lowercasing and pluralizing it (User → users).

Example: TypeScript With required On

Model name product, TypeScript, timestamps On, required On:

{"sku":"A-1","price":9.5,"created_at":"2026-10-01T09:30:00Z","release-date":"2026-10-01",
"variants":[{"color":"red","stock":3},{"color":"blue","size":"M"}],"meta":null}
import mongoose, { Schema } from 'mongoose';

export interface IVariants {
color: string;
stock: number;
size: string;
}

export interface IProduct {
sku: string;
price: number;
created_at: Date;
"release-date": string;
variants: IVariants[];
meta: any;
createdAt: Date;
updatedAt: Date;
}

const variantsSchema = new Schema({
color: { type: String, required: true },
stock: { type: Number, required: true },
size: { type: String, required: true },
});

const productSchema = new Schema<IProduct>({
sku: { type: String, required: true },
price: { type: Number, required: true },
created_at: { type: Date, required: true },
"release-date": { type: String, required: true },
variants: [variantsSchema],
meta: { type: mongoose.Schema.Types.Mixed, required: true },
}, { timestamps: true });

export default mongoose.model<IProduct>('Product', productSchema);

Two things to fix by hand before using it:

  • size and stock each appear in only one variant, yet both are required. The array elements are merged into one sub-schema with every key, and the switch applies to all of them.
  • meta was null, so it is Mixed and required: Mongoose would reject the very document you pasted. Give it a real type or drop required.

The interface is a plain document interface, passed as Schema<IProduct> and mongoose.model<IProduct>, as in the Mongoose TypeScript guide ("Using Generics"); it does not extend Document. With timestamps On, Mongoose adds createdAt and updatedAt of type Date (Timestamps), so the interface lists both and doc.createdAt type-checks on a document from new Product() and on a .lean() result. created_at from the JSON is a separate field. If the JSON already has a createdAt or updatedAt key, its own type is kept, because Mongoose then keeps that path as you defined it. The tool's test compiles every generated TypeScript file with TypeScript 5.9.3 in strict mode against Mongoose 9.10.3.

Keys that are not JavaScript identifiers, such as release-date, are quoted so the generated file parses.

Example: Every Sample Decides the Type

A root array with two orders, model name Order, JavaScript, timestamps Off:

[{"code":1,"note":null,"seller":{"meta":{"x":1}},"buyer":{"meta":{"y":"2"}}},{"code":"A-2","note":"gift","tags":["a",1]}]

Output:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const metaSchema = new Schema({
x: { type: Number },
});

const sellerSchema = new Schema({
meta: metaSchema,
});

const buyerMetaSchema = new Schema({
y: { type: String },
});

const buyerSchema = new Schema({
meta: buyerMetaSchema,
});

const orderSchema = new Schema({
code: { type: mongoose.Schema.Types.Mixed },
note: { type: String },
seller: sellerSchema,
buyer: buyerSchema,
tags: [mongoose.Schema.Types.Mixed],
}, { timestamps: false });

module.exports = mongoose.model('Order', orderSchema);
  • code is 1 in one order and "A-2" in the other, so it is Mixed; Number would reject "A-2". note is null once and "gift" once, so it is String. tags mixes a string and a number, so its elements are Mixed.
  • The two meta objects have different fields, so the second gets the parent key as a prefix (buyerMetaSchema). Objects under the same key with the same fields and types share one schema; if the prefixed name is taken too, a number is added.

The tool's test runs each generated JavaScript file with Mongoose 9.10.3, builds a document from every sample, and checks that validateSync() passes and that every field and value comes back (ISO date-times come back as Date, in toISOString() form; an array path missing from a sample comes back as [], Mongoose's default for arrays).

Limits

  • Mixed accepts anything. A field typed Mixed because its samples disagree is not cast or validated, and Mongoose does not track changes inside it unless you call markModified(). Pick one type when the data allows it.
  • Only one date format becomes Date. A string must start with YYYY-MM-DDThh:mm:ss. A database export such as 2026-10-08 09:30:00 stays String. A value with an offset (+08:00) is stored as that instant in UTC; MongoDB keeps no time zone with a date (Mongoose: Working With Dates).
  • Non-ASCII keys get placeholder schema names. Keys such as 收货地址 or 주소 are quoted and kept as paths, but the tool builds variable names from ASCII only, so the sub-schema becomes fieldSchema, and the next shape gets the parent prefix (orderFieldSchema with model name order). Rename them before you commit the file.
  • Only objects at the root. A schema describes documents, so in a root array the numbers, strings, null and arrays next to the objects are left out, and the status line says how many and which JSON types, for example Skipped 5 root array values that are not objects (number × 2, string, null, array).
  • Reserved path names stay, with a warning. Mongoose 9.10.3 lists collection, emit, errors, get, init, isModified, isNew, listeners, populated, remove, removeListener, save, toObject, validate as reserved (Schema.reserved in lib/schema.js). Such a key stays a path and the value is stored, but Mongoose prints a warning, and on a document the field value replaces the method or property of the same name (errors and isNew are properties): with a field named save, doc.save is the value and doc.save() fails. The status line names these keys; get and toObject also break a document, so it names them with the next group. The suppressReservedKeysWarning schema option only hides the warning, so the tool does not add it; rename the key instead.
  • Other document member names can break a document. Mongoose warns only about the reserved names, but a document has more members, and the status line names two groups of keys checked against Mongoose 9.10.3 documents. Mongoose itself uses the document members (methods and properties) of the first group, so such a field can make building, validating or serializing a document fail, and the status line uses the warning color: with a field named markModified, new Model() throws this.markModified is not a function; _doc ends in Maximum call stack size exceeded; schema works while the input has only schema keys, then fails on any other key with Cannot read properties of undefined (reading 'discriminatorKey'); toJSON makes JSON.stringify(doc) print Mongoose's internal state ($__, _doc). This group is _doc, __index, __parentArray, get, isDirectModified, markModified, modifiedPaths, schema, toBSON, toJSON, toObject and validateSync, plus 29 names that start with $ (get and toObject are also reserved). For 83 other names Mongoose shows no warning, and the field value only replaces the method or property: with fields named model and set, doc.model and doc.set are the field values. The tool's test rebuilds both groups from real Mongoose 9.10.3 documents. Rename such keys.
  • Three key names never become paths. Mongoose 9.10.3 skips schema keys named __proto__, constructor and prototype (lib/schema.js, to avoid prototype pollution). The output still lists them, with __proto__ written as ["__proto__"] so the object literal does not set its prototype, and the status line names them; rename these keys before you store such data.
  • The model name is a string. It goes into mongoose.model() in PascalCase with quotes and backslashes escaped (it's → 'It\'s'); variable and interface names use only ASCII letters, digits, _ and $.
  • No ObjectId, enum, index or validation. A 24-character hex string stays String; add Schema.Types.ObjectId and ref, unique, enum or min/max yourself.
  • Only the root schema is typed. Sub-schemas get an interface for the root interface to use, but new Schema() for them has no type argument, and fields are not optional even when required is Off. Mongoose does not check that the interface matches the schema (TypeScript guide), so mark optional fields with ? yourself.
  • A root array of primitives such as ["a", "b"] generates no schema, only the comment // Array of primitives — no schema to generate.

For plain TypeScript types or a Zod schema from the same JSON, use JSON to TypeScript or JSON to Zod.

FAQ

What does this tool generate?

It generates Mongoose schema definitions from JSON. Nested objects become sub-schemas that are written before the schema that uses them (objects under the same key with the same fields share one), and a model export is included at the bottom.

What language modes are supported?

JavaScript (CommonJS require/module.exports) and TypeScript (ES module import/export with a plain document interface passed to Schema<T> and model<T>, as in the Mongoose TypeScript guide).

How are JSON types mapped to Mongoose types?

string → String, and a string that starts like an ISO 8601 date-time (2026-10-01T09:30:00Z) → Date; number → Number; boolean → Boolean; a field that is null in every sample, or whose samples have different types → mongoose.Schema.Types.Mixed; array of primitives → [Type] (date-times inside an array stay String); array of objects without null elements → [subSchema]; nested object → sub-schema.

What does the timestamps option do?

When On, the schema is created with { timestamps: true }, which automatically adds createdAt and updatedAt fields managed by Mongoose. In TypeScript mode the interface also lists createdAt: Date and updatedAt: Date, unless your JSON already has a key with that name.

Are all fields marked as required?

Not by default, since a JSON sample cannot show which fields are required. Turning the required switch On adds required: true to every field except nested schemas and arrays of objects; then remove it where a field is optional. Note that Mongoose's required validator rejects null, so a field that is null in your sample cannot stay required.

Is my data sent to a server?

No. The JSON and the model name are processed in this browser tab and are not sent anywhere, and the tool does not save them in browser storage. The page records an analytics event with only the tool name and the action (generate) when you finish an edit (the field loses focus), click Example or change an option, but not again when the JSON, model name and options are the same as for the previous event.