Mongoose
save
insert
create
database operations

mongoose save vs insert vs create

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Mongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. One of its core features is interacting with MongoDB databases more easily and efficiently. When working with Mongoose, you often encounter methods like save(), insertMany(), and create(). These methods are crucial for manipulating documents in a MongoDB collection but differ in functionality and usage. This article delves into the technical differences and usage examples of each method.

Mongoose save()

Overview

The save() method is an instance method provided by Mongoose to save individual documents to the database. It has two major functionalities:

  1. Persist new documents in the collection.
  2. Update existing documents' fields.

Usage

To use save(), you need an instance of a Mongoose model. This is because save() operates on document instances, not the model itself.

Example

javascript
1const mongoose = require('mongoose');
2const Schema = mongoose.Schema;
3
4const userSchema = new Schema({ name: String, age: Number });
5const User = mongoose.model('User', userSchema);
6
7// Creating a new user
8const newUser = new User({ name: 'Alice', age: 25 });
9
10newUser.save((err) => {
11  if (err) return console.error(err);
12  console.log('Document saved');
13});
14
15// Updating an existing user
16User.findOne({ name: 'Alice' }, (err, user) => {
17  if (err) return console.error(err);
18  if (!user) return;
19
20  user.age = 26;
21  user.save((err) => {
22    if (err) return console.error(err);
23    console.log('Document updated');
24  });
25});

Mongoose insertMany()

Overview

insertMany() is a static method on the Mongoose model used to insert multiple documents into a collection at once. It's highly efficient for batch inserts because it sends all documents in a single operation.

Usage

This method is called on the model itself and accepts an array of plain objects or Mongoose documents.

Example

javascript
1User.insertMany([
2  { name: 'Bob', age: 30 },
3  { name: 'Charlie', age: 35 }
4], (err, docs) => {
5  if (err) return console.error(err);
6  console.log('Documents inserted:', docs);
7});

Mongoose create()

Overview

create() is a combination of the instantiation and save() process. It can be thought of as a shortcut method that creates and saves documents in one go.

Usage

create() operates on the model and can handle one or multiple documents.

Example

javascript
1// Creating and saving a single document
2User.create({ name: 'Daniel', age: 40 }, (err, doc) => {
3  if (err) return console.error(err);
4  console.log('Document created:', doc);
5});
6
7// Creating and saving multiple documents
8User.create([{ name: 'Eve', age: 45 }, { name: 'Frank', age: 50 }], (err, docs) => {
9  if (err) return console.error(err);
10  console.log('Documents created:', docs);
11});

Key Differences

Here's a table summarizing the key points of save(), insertMany(), and create():

MethodOperates OnUse Case (Single vs. Multiple)Instance vs. ModelTriggers MiddlewareAtomicity
save()Document InstancesSingleInstanceYesNo
insertMany()ModelMultipleModelNo (bulk)Yes
create()ModelSingle or MultipleModelYesNo

Additional Details

  • Atomicity: While insertMany() is atomic for inserting a batch, neither save() nor create() provide atomic guarantees when dealing with multiple document inserts.
  • Middleware: save() and create() trigger Mongoose middleware (pre, post hooks), while insertMany() does not trigger middleware by default unless specified.
  • Error Handling: insertMany() offers better error handling for batch operations, allowing you to continue processing even if some documents fail to insert.

By understanding these nuances, developers can make more informed choices about which method to use based on their specific needs and contexts, ensuring both performance and data integrity are maintained.


Course illustration
Course illustration

All Rights Reserved.