Back

Mongoose basics

Mongoose is a library that adds schemas, validation, and simple methods on top of MongoDB in Node. You define a schema, create a model from it, then use the model to read and write data.

import mongoose from "mongoose"

await mongoose.connect(process.env.MONGODB_URI!)

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  age: Number,
}, { timestamps: true })

const User = mongoose.model("User", userSchema)

await User.create({ name: "Daniel", email: "d@example.com" })
const users = await User.find({ age: { $gte: 18 } })
await User.findByIdAndUpdate(id, { age: 21 })
await User.findByIdAndDelete(id)

Roadmap