JSON to Mongoose schema and TypeScript interface

Paste one JSON document or an array of them and get a Mongoose schema with types, sub-schemas, required fields, enum guesses, ObjectId and Date detection and the timestamps option. The TypeScript interface comes with it, with notes for Mongoose 9.

Updated

Several documents give better results: a key missing from some becomes optional, and a field with a few repeated values can become an enum.

Singular and PascalCase. Nested objects are named from their keys: orders becomes Order.

Needs at least 5 documents and every value repeated at least once on average.

Mongoose schema

8 top-level paths

6 documents read, 2 sub-schemas, 12 paths in all

Mongoose schema

import mongoose, { Schema } from "mongoose";

const addressSchema = new Schema({
  city: { type: String, required: true },
  pin_code: { type: String, required: true },
}, { _id: false });

const orderSchema = new Schema({
  order_id: { type: Number, required: true },
  total: { type: Number, required: true },
}, { _id: false });

const userSchema = new Schema({
  email: { type: String, required: true },
  role: { type: String, required: true, enum: ["admin", "editor", "viewer"] },
  age: { type: Number, required: true },
  phone: String,
  address: { type: addressSchema, required: true },
  tags: [String],
  team_id: { type: Schema.Types.ObjectId, ref: "Team" },
  orders: [orderSchema],
}, { timestamps: true });

// Index hints (commented out: each index costs write time and memory; add the ones your queries use)
// userSchema.index({ email: 1 }, { unique: true }); // if values must be unique (an optional field needs a sparse or partial index)
// userSchema.index({ role: 1 }); // only if you filter by it often
// userSchema.index({ phone: 1 }, { unique: true }); // if values must be unique (an optional field needs a sparse or partial index)
// userSchema.index({ team_id: 1 }); // you will probably query by this reference
// userSchema.index({ createdAt: -1 }); // newest-first lists

export default mongoose.model("User", userSchema);

// ── types.ts (TypeScript interface for the same schema) ──
// import { Types } from "mongoose";
// export interface IUser {
//   email: string;
//   role: string;
//   age: number;
//   phone?: string;
//   address: IAddress;
//   tags: string[];
//   team_id?: Types.ObjectId | null;
//   orders: IOrder[];
// }

// export interface IOrder {
//   order_id: number;
//   total: number;
// }

// export interface IAddress {
//   city: string;
//   pin_code: string;
// }
  • “_id” was left out: Mongoose adds an ObjectId _id to every schema and subdocument that doesn't turn it off.
  • “role” got enum: ["admin", "editor", "viewer"] because only 3 different values appear in 6 samples. That is a guess from the sample; check it against the real list of values before keeping it.
  • "createdAt" and "updatedAt" left the field list and became the timestamps option: Mongoose then sets and updates them itself on save.
  • Arrays are never marked required: Mongoose gives every array path a default of [], so it is always present on a saved document.
  • A ref only names the model for populate(); it does not check that the target exists. Make sure a model with that exact name is registered.
  • This output uses Schema, Schema.Types, timestamps, enum, ref and schema.index(), and none of them is among the schema changes in the Mongoose 9 migration guide. The version on npm on 2026-11-11 was 9.12.1, which needs Node 20.19 or newer. Mongoose 9 renamed FilterQuery to QueryFilter in its TypeScript types and no longer accepts a background option in schema.index() (migration guide).
  • Mongoose checks that every schema path exists in the interface but does not check that required and optional match, so keep the ? marks in step with required: true yourself. Array paths are typed without ? because Mongoose defaults them to [].
  • Sub-schemas are separate Schema objects, so each can have its own validators and indexes; arrays of them are DocumentArrays with their own _id unless _id: false is set.

How is a Mongoose schema inferred from JSON?

Every key becomes a schema path. A string becomes String, a number Number, true or false Boolean. A string that matches an ISO 8601 date in every document becomes Date, and a string of exactly 24 hex characters in every document becomes Schema.Types.ObjectId. A key that holds different types in different documents becomes Schema.Types.Mixed, because Mongoose has no union type.

When you paste an array of documents, each key is counted. A key present and non-null in every document gets required: true; a key missing from some, or null in some, is optional. A string field that takes only a few repeated values across at least five documents gets an enum guess (limit adjustable), flagged as a guess because a sample cannot show every legal value.

Nested objects become sub-schemas (or inline nested paths if you choose), and arrays of objects become arrays of those sub-schemas. createdAt and updatedAt date fields at the top level are removed from the field list and turned into the timestamps option, with custom names mapped when you use created_at or updated_at. The TypeScript interface is written from the same tree.

"2026-03-14T09:30:00Z"        -> Date
"65a1f0c2e4b0a1b2c3d4e5f6"   -> Schema.Types.ObjectId
"role": admin | editor | viewer (6 docs) -> String, enum guess
key in 4 of 6 documents        -> optional (no required)

How does each JSON value map to a Mongoose type and a TypeScript type?

Type mapping used on this page
In the JSONMongoose schemaTypeScript interfaceNotes
"text"StringstringEnum only if you allow the guess
42 or 4.2NumbernumberMongoose has no separate integer here; the check flags integers past 2^53
trueBooleanboolean
"2026-03-14T09:30:00Z"DateDateNeeds every value in that field to be a valid ISO date
24 hex charactersSchema.Types.ObjectIdTypes.ObjectIdA ref is added from names like team_id
{ ... }Sub-schema or nested pathIts own interface_id: false when the samples have none
[ ... ][Type] or [subSchema]Type[]Not marked required; Mongoose defaults it to []
null only, empty array, or mixed typesSchema.Types.MixedunknownNo casting; call markModified after changes

How to turn JSON into a Mongoose schema

  1. 1
    Paste several documentsA single object works, but an array of five or more lets the page see which keys are optional and which strings repeat.
  2. 2
    Pick the output and the optionsChoose import, require or TypeScript. Leave timestamps on Detect so createdAt and updatedAt turn into the option, and decide whether enum guesses and refs fit your data.
  3. 3
    Review the notesMixed paths, renamed keys, enum guesses and required fields are listed. Fix anything the sample could not show, such as an enum with values that never appeared.
  4. 4
    Copy it into your projectSave the schema file, import the interface where you type your queries, and uncomment only the index hints you will really query by. The MongoDB query builder here gives the ESR order for compound indexes.

Frequently asked questions

What does Mongoose use for an ObjectId type in a schema?
Schema.Types.ObjectId, usually with a ref naming another model so populate() can fetch it. In the TypeScript interface the field is typed Types.ObjectId. This page uses it for any field where every value is a 24-character hex string, and adds a ref when the key looks like team_id or teamIds.
Why are createdAt and updatedAt missing from my schema?
They were turned into the timestamps option. With timestamps: true, Mongoose adds both paths and keeps them current on save. Names like created_at are kept through timestamps: { createdAt: "created_at" }. Set Timestamps to None if you want them as ordinary fields.
Why is my array not marked required?
Mongoose gives array paths a default of an empty array, so they exist on every document you save. A required validator on an array would add nothing but confusion, so this page skips it and types the array in the interface without a question mark.
Is the enum safe to keep?
Treat it as a draft. The page only sees the values in your sample; a real status field may have values that never appeared there, and a Mongoose enum rejects anything else on validation. Compare with the real list, or set the enum limit to 0 to switch guessing off.
What changed for schemas between Mongoose 8 and 9?
The migration guide lists, among others: pre hooks no longer receive next(), UUID values are bson.UUID instances, schema.index() drops the background option, and FilterQuery is now QueryFilter in the TypeScript types. Node 20.19 or newer is required. A plain schema like the one generated here doesn't use any removed feature.
When should a nested object be a sub-schema instead of inline?
Use a sub-schema when you want to reuse the shape, give it its own validators, or put it in an array, where each element becomes a subdocument. Inline nested paths are lighter for a single object such as an address, but they can't carry required or other options on the nested object itself.
Is it safe to paste real customer documents?
Yes for privacy: the JSON is parsed and the schema written inside the page and nothing is uploaded. Still, remove secrets such as tokens and password hashes first, because the sample can show up in your screen recordings and clipboards.

Sources

Related tools

See all 135 free tools

Need a custom dev tool for your team?

We build internal tools, dashboards, APIs, and SaaS platforms. If you can describe it, we can ship it.

Built by CountryDevs · No signup · No ads · We count visits, never what you enter