Sikau

MongoDB · Day 9 · about 25 min

Schemas: validation and Mongoose

Flexible doesn't mean messy.

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();

The rest of this lesson

  • Validation inside MongoDBexplain
  • Mongoose models in an appexplain
  • Where are rules enforced?predict
  • Which layer does it?match
  • Validator in actionpredict
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB