How to use Mongoose Save

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

The insert() and insertMany() methods are both valuable functions for inserting documents into an established MongoDB collection. An additional and worthwhile method that can be used to easily insert documents into a Mongoose collection is the save() method. The save() method is designed to insert documents by calling the instance of that document, meaning the model that has been created. This tutorial will provide easy to follow instructions and examples that clearly demonstrate how to use the Mongoose save function to insert documents into a MongoDB collection.

Prerequisites

  • MongoDB must be properly set up and functioning in order to use the Mongoose save() method to insert documents into a MongoDB collection.

Connection with MongoDB

The save() method can be used in a file where the schema and model for a collection was created.

Begin by creating a file named “savemodel.js” and then execute the following command to import mongoose in the file:

1
var mongoose = require("mongoose");

Now execute the following command to use mongoose to make a connection with the MongoDB database:

1
2
3
4
5
6
var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myDB", {
  useUnifiedTopology: true,
  useNewUrlParser: true
});

Note that the name of the database is “myDB”.

Now execute the following command to obtain a reference to the database:

1
2
3
4
5
6
7
8
var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myDB", {
  useUnifiedTopology: true,
  useNewUrlParser: true
});

var db = mongoose.connection;

Now complete the connection protocol by adding the following “success” and “error” messages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myDB", {
  useUnifiedTopology: true,
  useNewUrlParser: true
});

var db = mongoose.connection;

db.on("error", console.error.bind(console, "connection error:"));

db.once("open", function() {
  console.log("Connection Successful!");
});

As shown in the following screenshot, the connection has been completed:

Image from Gyazo

Schema

The next step requires creating the new schema. Here each document will consist of the two properties: “name” and “age.”

As shown in the following example, the name property will store string values and the age property will store numerical values:

1
2
3
4
var schema = mongoose.Schema({
  name: String,
  age: Number
});

With the schema now ready, execute the following command to create the model for the schema:

1
2
3
4
5
6
var schema = mongoose.Schema({
  name: String,
  age: Number
});

var Model = mongoose.model("model", schema, "myCollection");

Mongoose save

With the schema and model set up, the mongoose save() method can now be used to insert a document into the “myCollection” collection. Execute the following command to create an instance of a document:

1
var doc1 = new Model({ name: "John", age: 21 });

The above document can now be used to call the save() method.

While the save() method takes a callback function as a parameter, the callback function itself has two parameters: 1) error, should one occur; and 2) the document that is inserted into the collection. Refer to the following example:

1
2
3
4
5
6
var doc1 = new Model({ name: "John", age: 21 });

doc1.save(function(err, doc) {
  if (err) return console.error(err);
  console.log("Document inserted succussfully!");
});

Wrapping it up

Execute the following example to see how everything covered so far works together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myDB", {
  useUnifiedTopology: true,
  useNewUrlParser: true
});

var db = mongoose.connection;

db.on("error", console.error.bind(console, "connection error:"));

db.once("open", function() {
  console.log("Connection Successful!");
});

var schema = mongoose.Schema({
  name: String,
  age: Number
});

var Model = mongoose.model("model", schema, "myCollection");

var doc1 = new Model({ name: "John", age: 21 });

doc1.save(function(err, doc) {
  if (err) return console.error(err);
  console.log("Document inserted succussfully!");
});

Image from Gyazo

Now verify the results through the Mongo shell:

Image from Gyazo

As shown in the updated second screenshot, the document has been successfully inserted!

Conclusion

This tutorial provided instructions and examples that demonstrated how to use the Mongoose save() method to insert documents into a MongoDB collection. The tutorial covered how to use mongoose to set up and make a connection with the MongoDB database, how to obtain a reference to the database and complete the connection protocol by adding the “success” and “error” messages. The article then explained the steps required for creating a new schema and the “name” and “age” properties used in the document schema. The tutorial then covered how to execute the mongoose save() method to insert a document into the collection by creating an instance of that document. The tutorial then provided a working example of how the save function works to insert documents into a MongoDB collection. Remember that the name property stores string values and the age property stores numerical values when creating the document schema. It should also be kept in mind that while the save() method takes a callback function as a parameter, the callback function itself has two parameters, an error parameter and the document that is inserted into the collection.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.