Generate a complete Mongoose schema
A Mongoose model is more than a list of fields — it carries types, validators, references, indexes, and the compiled model() export. This builder turns a model name and a short field list into a ready-to-require schema file so you stop copying the same boilerplate between collections.
How it works
You name the model and list fields as name type with optional flags like required or unique. The builder maps each type to the correct Mongoose declaration:
str / string -> { type: String }
num / number -> { type: Number }
bool / boolean -> { type: Boolean, default: false }
date -> { type: Date }
ref:Model -> { type: Schema.Types.ObjectId, ref: 'Model' }
[str] -> [String]
Flags add options inline: required appends required: true, unique appends unique: true. The schema is created with { timestamps: true } so createdAt and updatedAt are managed automatically. Fields flagged unique also trigger a comment noting the implicit index, and the builder adds a schema.index(...) example for compound queries. Finally it exports the compiled model with module.exports = mongoose.model('Name', schema).
Tips and notes
- Reference fields work with
populate():Order.find().populate('user')swaps the stored ObjectId for the full referenced document at query time. unique: truedefines an index, not a validator. A duplicate insert throws a MongoServerError at write time, so catch thecode === 11000case in your route.- For enumerated values, add
enum: ['a', 'b']to a String field; the builder leaves a commented example showing where. - Keep model names singular and CapitalCase. Mongoose pluralises and lowercases them to derive the collection name (
Userbecomes theuserscollection).