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
Scan with WeChat to share this tool
Examples, details and FAQ Worked examples, how it compares with other tools, and answers to common questions.
Type Mapping
nullfits any type and is skipped; a field that isnullin 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 as2026-10-01, a date-time with a space instead ofT(2026-10-01 09:30:00) and date-times inside an array stayString - 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:
sizeandstockeach appear in only one variant, yet both arerequired. The array elements are merged into one sub-schema with every key, and the switch applies to all of them.metawasnull, so it isMixedandrequired: Mongoose would reject the very document you pasted. Give it a real type or droprequired.
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);
codeis1in one order and"A-2"in the other, so it isMixed;Numberwould reject"A-2".noteisnullonce and"gift"once, so it isString.tagsmixes a string and a number, so its elements areMixed.- The two
metaobjects 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
Mixedbecause its samples disagree is not cast or validated, and Mongoose does not track changes inside it unless you callmarkModified(). 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 as2026-10-08 09:30:00staysString. 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 becomesfieldSchema, and the next shape gets the parent prefix (orderFieldSchemawith model nameorder). 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,validateas reserved (Schema.reservedin 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 (errorsandisNeware properties): with a field namedsave,doc.saveis the value anddoc.save()fails. The status line names these keys;getandtoObjectalso break a document, so it names them with the next group. ThesuppressReservedKeysWarningschema 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()throwsthis.markModified is not a function;_docends inMaximum call stack size exceeded;schemaworks while the input has only schema keys, then fails on any other key withCannot read properties of undefined (reading 'discriminatorKey');toJSONmakesJSON.stringify(doc)print Mongoose's internal state ($__,_doc). This group is_doc,__index,__parentArray,get,isDirectModified,markModified,modifiedPaths,schema,toBSON,toJSON,toObjectandvalidateSync, plus 29 names that start with$(getandtoObjectare also reserved). For 83 other names Mongoose shows no warning, and the field value only replaces the method or property: with fields namedmodelandset,doc.modelanddoc.setare 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__,constructorandprototype(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; addSchema.Types.ObjectIdandref,unique,enumormin/maxyourself. - 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 whenrequiredis 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.