Structure when you need it
MongoDB doesn't force a schema — but your app still expects price to be a number. Teams add structure two ways: schema validation inside MongoDB, and Mongoose schemas in Node.js code.
Two layers of rules
db.createCollection("dishes", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: { bsonType: "string", minLength: 2 },
price: { bsonType: "int", minimum: 1 },
tags: { bsonType: "array", items: { bsonType: "string" } },
},
},
},
});import mongoose from "mongoose";
const dishSchema = new mongoose.Schema(
{
name: { type: String, required: true, trim: true },
price: { type: Number, required: true, min: 1 },
tags: [String],
},
{ timestamps: true },
);
export const Dish = mongoose.model("Dish", dishSchema);
await mongoose.connect(process.env.MONGODB_URI);
const momo = await Dish.create({ name: " Momo ", price: 180 });
const cheap = await Dish.find({ price: { $lt: 100 } }).sort({ price: 1 }).lean();