Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

Your First Mongoose Model and Document

Define your first Mongoose schema, compile a model, create a document, save it to MongoDB and read it back. A complete beginner walkthrough.

Time to put the pieces together. In this lesson you will write a complete small program: connect, define a schema, compile a model, create a document, save it and find it again. We will go through every line, and then use a runnable stand-in to watch what each step does to the data.

The complete program

JavaScript
// app.js
import mongoose from 'mongoose';

await mongoose.connect('mongodb://127.0.0.1:27017/library');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  pages: Number,
  published: { type: Date, default: Date.now },
});

const Book = mongoose.model('Book', bookSchema);

const book = new Book({ title: 'Dune', author: 'Frank Herbert', pages: 412 });
await book.save();
console.log(book);

const found = await Book.findOne({ author: 'Frank Herbert' });
console.log(found.title);

await mongoose.connection.close();

Run it with node app.js. The first console.log(book) prints something like this:

TEXT
{
  title: 'Dune',
  author: 'Frank Herbert',
  pages: 412,
  published: 2026-11-13T09:30:00.000Z,
  _id: new ObjectId('6733a1f2c0ffee0012345678'),
  __v: 0
}

Your _id and date will differ. Let us look at everything in it.

Line by line

The schema. new mongoose.Schema({...}) takes an object that maps field names to types. title: String is shorthand for title: { type: String }. The published field uses the long form because it needs an option, default. Passing the function Date.now (not calling it) means every new document gets the time of its creation, not the time the schema was defined.

The model. mongoose.model('Book', bookSchema) registers the schema under the name Book and returns a model class. By convention, model variables are capitalised singular nouns. The collection is books.

The document. new Book({...}) creates a document in memory only. Nothing is in the database yet. Notice that Mongoose has already filled in published and generated an _id.

Saving. await book.save() validates the document and inserts it. save() returns a promise; forgetting await is the most common beginner bug, because the program may exit or read before the write finishes.

Finding. Book.findOne({ author: ... }) queries the books collection and returns the first matching document, or null if nothing matches. The result is a full Mongoose document, with all of its methods, not a plain object.

The extra fields you did not write

Field Where it comes from
_id Added automatically as an ObjectId, a 12-byte unique value, unless you define your own _id type.
__v The version key, an integer Mongoose uses to detect some array update conflicts. You can ignore it for now.

Every document in MongoDB needs an _id. Mongoose generates it when you create the document in memory, not when the database stores it, so you can use book._id before saving.

Fields not in the schema are dropped

Mongoose runs in strict mode by default. Values for fields that the schema does not declare are silently ignored on save:

JavaScript
const odd = new Book({ title: 'Emma', color: 'blue' });
console.log(odd.color); // undefined

That is a feature: it stops typos and malicious extra fields from reaching the database. You can change it with the strict schema option, covered in Schema options and defaults.

Casting: Mongoose converts values

If you give a field a value of the wrong type, Mongoose first tries to cast it:

JavaScript
const b = new Book({ title: 'Emma', pages: '474' });
console.log(typeof b.pages); // 'number'

The string '474' became the number 474. If casting is impossible (pages: 'many'), saving fails with a CastError or a validation error. Casting rules are one of the features that make Mongoose pleasant for data arriving from forms and JSON requests, where numbers often show up as strings.

Stand-in: seeing the steps

Real Mongoose needs a server, so here is a plain Node.js stand-in (not Mongoose). It imitates the three stages of a document's life: construct (defaults, casting, strict mode), save (store) and find.

Node.js Build, save and find a document (stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You can see the unknown color field being dropped, the string '412' cast to a number and the default filling the missing date. Real Mongoose does all of this inside the model constructor.

Creating in one step

Model.create() builds and saves in one call and accepts one object or an array:

JavaScript
const created = await Book.create({ title: 'Emma', author: 'Jane Austen', pages: 474 });

await Book.create([
  { title: 'Persuasion', author: 'Jane Austen', pages: 249 },
  { title: 'Hamlet', author: 'William Shakespeare', pages: 160 },
]);

Use new Book().save() when you want to change the document between creation and saving; use create() when you already have all the data.

Looking at what a document is

A document is not a plain object. To get plain data, call toObject() or toJSON(). JSON.stringify(doc) calls toJSON() automatically, which is why you can send documents straight to res.json() in Express.

Node.js Why plain objects are handy (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first line prints FakeDocument {} because the data is held privately. Real Mongoose documents hold their state in internal properties too, which is why logging them with console.log prints a tidy summary but code should always read fields through the document (doc.title) or call toObject().

Common first-model mistakes

  • Forgetting await on save(), create() and queries.
  • Calling a default function (default: Date.now()) so all documents share one timestamp.
  • Reusing a model name for different schemas; registering Book twice throws OverwriteModelError.
  • Expecting unknown fields to be stored. Strict mode drops them.
  • Not closing the connection in a script, so the process hangs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a new document get its _id?

    Mongoose generates the ObjectId when you construct the document, so you can read _id before saving.
  2. 2. What is wrong with default: Date.now() in a schema?

    Pass the function itself (Date.now) so Mongoose calls it for each new document.
  3. 3. A schema has no field named color. What happens to new Book({ color: 'blue' }).color in default strict mode?

    Strict mode ignores fields that are not in the schema.
  4. 4. Which call creates and saves a document in one step?

    Model.create() constructs and saves. It also accepts an array to insert several documents.

Summary

  • A schema describes fields, mongoose.model() turns it into a model, and new Model() makes a document in memory.
  • save() and create() validate and write; always await them.
  • Mongoose adds _id and __v, fills defaults, casts values and drops unknown fields in strict mode.
  • Documents are rich objects; use toObject() or toJSON() for plain data.

Next: How Mongoose works: buffering and the connection pool