Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท CRUD and Queries

Creating Documents in Mongoose

Insert data with Mongoose: new Model().save(), Model.create(), insertMany with ordered and unordered options, handling duplicate key and validation errors.

CRUD stands for create, read, update and delete. This chapter covers all four with Mongoose; we start with create. There are three main ways to insert documents, and each fits a different situation: new Model().save(), Model.create() and Model.insertMany(). You will also learn what errors to expect and how to handle them.

All examples in this chapter use this model:

JavaScript
import mongoose from 'mongoose';

const productSchema = new mongoose.Schema({
  sku: { type: String, required: true, unique: true },
  name: { type: String, required: true, trim: true },
  price: { type: Number, required: true, min: 0 },
  tags: [String],
  inStock: { type: Boolean, default: true },
}, { timestamps: true });

const Product = mongoose.model('Product', productSchema);

new and save()

Construct a document in memory, modify it if needed, then save:

JavaScript
const p = new Product({ sku: 'KB-100', name: '  Keyboard ', price: 49.9 });
p.tags.push('office');
const saved = await p.save();

console.log(saved === p);   // true, save resolves with the same document
console.log(saved.name);    // 'Keyboard' (the trim option cleaned it)

save() validates, applies defaults and timestamps, and inserts the document (for a new document) or updates it (for an existing one). Use this form when you need to work with the document before saving, for example to read the generated _id or call an instance method.

Model.create()

create() is shorthand for constructing and saving:

JavaScript
const keyboard = await Product.create({ sku: 'KB-100', name: 'Keyboard', price: 49.9 });

Passing an array creates several documents; each is validated and saved separately, and the returned array holds the saved documents:

JavaScript
const items = await Product.create([
  { sku: 'MS-200', name: 'Mouse', price: 19.5 },
  { sku: 'MN-300', name: 'Monitor', price: 189 },
]);
console.log(items.length); // 2

To pass options such as session or ordered, use the array form: Product.create([doc1, doc2], { ordered: true }).

Model.insertMany()

For bulk inserts, insertMany() is much faster because it sends all documents to MongoDB in one command (or a few batches), instead of one write per document:

JavaScript
const result = await Product.insertMany([
  { sku: 'HD-400', name: 'Headset', price: 59 },
  { sku: 'WC-500', name: 'Webcam', price: 79 },
]);

It validates every document first. By default (ordered: true) the first failure stops the insert; with { ordered: false } it keeps going and reports all errors at the end. Two useful options:

JavaScript
await Product.insertMany(docs, { ordered: false });                 // continue past errors
await Product.insertMany(docs, { ordered: false, rawResult: true }); // get details of what happened

insertMany does not run pre('save') middleware (it runs pre('insertMany') instead), so logic you depend on in save hooks may need a separate hook or a different method. Document middleware explains the difference.

Method Writes Save hooks run? Best for
new Model().save() one yes custom steps before saving
Model.create() one or many, separately yes simple creates, small arrays
Model.insertMany() many, batched no imports, seeding, large arrays

What goes wrong

Two kinds of error appear when creating documents.

Validation errors come from Mongoose, before anything is sent. The error object has name: 'ValidationError' and an errors map keyed by field path:

JavaScript
try {
  await Product.create({ name: 'No sku', price: -5 });
} catch (err) {
  if (err.name === 'ValidationError') {
    for (const [path, e] of Object.entries(err.errors)) {
      console.log(path, '->', e.message);
    }
  }
}
// sku -> Path `sku` is required.
// price -> Path `price` (-5) is less than minimum allowed value (0).

Duplicate key errors come from MongoDB when a unique index is violated. They have code: 11000 and the clashing value in keyValue:

JavaScript
try {
  await Product.create({ sku: 'KB-100', name: 'Another', price: 10 });
} catch (err) {
  if (err.code === 11000) {
    console.log('Duplicate:', err.keyValue); // { sku: 'KB-100' }
  }
}

Duplicate detection needs the unique index to exist. Mongoose builds declared indexes in the background after connecting (autoIndex); on a brand-new collection a very fast second insert can in theory race the index build. Production systems create indexes ahead of time (see the indexes chapter) and call await Product.init() in tests to wait for them.

Never rely on "check if it exists, then insert" for uniqueness. Two requests can both pass the check. Let the unique index decide and handle 11000.

Stand-in: creating with validation and uniqueness

This runnable stand-in is not Mongoose, but it mimics both error types, the difference between ordered and unordered bulk inserts, and error shapes.

Node.js create, insertMany ordered vs unordered (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.

Ordered mode stops at the first failure after inserting one document; unordered inserts every valid document and collects the failures.

Using the returned document

After save() or create() the document is fully populated: it has its _id, defaults, timestamps and trimmed or lowercased values. That is the object to return from an API handler:

JavaScript
app.post('/products', async (req, res) => {
  try {
    const product = await Product.create(req.body); // strict mode drops unknown fields
    res.status(201).json(product);
  } catch (err) {
    if (err.name === 'ValidationError') return res.status(400).json({ errors: err.errors });
    if (err.code === 11000) return res.status(409).json({ message: 'SKU already exists' });
    throw err;
  }
});

Be careful with Product.create(req.body): strict mode ignores unknown fields, but a client may still set fields you did not intend (inStock, a role, a price). Pick the allowed fields explicitly when it matters.

Common mistakes

  • Missing await, so errors become unhandled rejections.
  • Using insertMany and expecting pre('save') hooks to run.
  • Checking for duplicates in application code instead of relying on a unique index.
  • Forgetting that Model.create() with an array saves in parallel; order of insertion is not guaranteed unless you pass { ordered: true }.
  • Passing req.body straight into create() without selecting fields.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method is fastest for inserting thousands of documents?

    insertMany sends documents in batches instead of one write per document.
  2. 2. What error code signals a duplicate key violation from MongoDB?

    A unique index violation is reported by MongoDB as error code 11000, with the clashing value in keyValue.
  3. 3. What does insertMany with { ordered: false } do when one document fails?

    Unordered inserts continue past errors and report them at the end.
  4. 4. Which approach correctly enforces unique SKUs?

    The check-then-insert pattern has a race condition. The index is the real guarantee.

Summary

  • Create documents with new Model().save(), Model.create() (one or many) or Model.insertMany() for bulk.
  • insertMany is faster but skips save hooks; ordered: false continues past failures.
  • Handle ValidationError (from Mongoose, with errors by path) and duplicate key error 11000 (from MongoDB).
  • Rely on unique indexes, not check-then-insert, for uniqueness.
  • Limit what request data can reach create().

Next: Finding documents