Open In App

Mongoose Documents Updating Using save()

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An important aspect of a mongoose model is to save the document explicitly when changes have been made to it. This is done using the save() method. In this article, we will see its uses and see the things we should keep in mind while saving our document.

We will take the help of an example to understand the save() operation.

Step 1: Creating a Model:

Open an empty folder in VS Code, and create a file with the name, app.js. Now, open the terminal and write the following command in it, to initialize this folder as a NodeJS project.

npm init -y

Now, write the following commands to download the MongoDB and mongoose packages from the NPM repository.

npm install mongodb mongoose

Now, the next thing we do is import the mongoose library into our file, assign it to a constant, and call the connect method on that constant to connect to a MongoDB database. We are connecting to a local database, you can also connect to a cloud database, but it needs to be a MongoDB database. Pass the URL string to connect method exactly as shown(for local DB), you can change the name of the database to your liking.

In mongoose, first, a blueprint needs to be built from which collections(or models) and their documents are created. This blueprint is called schema. We call the Schema method and pass it an object, where keys are the fields that we want to have on each document, and their respective values are the data types of those keys. We assign this to a constant as well.

Next, we call the model method on the mongoose object and pass it a string, which is the name of our collection, and the constant that holds the schema. The name defined in the string must be title case and singular, mongoose will automatically convert it to small case and plural. This creates a model/collection on our heroesDB database. Although it is empty right now since we have not created any documents for it.

Javascript




// Importing mongoose library and connecting to a MongoDB database
const mongoose = require("mongoose")
 
// Creating a blueprint of each of our document
let heroSchema = mongoose.Schema({
    name: {
        type: String,
        require: true
    },
    power: {
        type: String,
        require: true
    },
    rank: String
})
 
// Creating a collection/model to hold all these documents
let Hero = mongoose.model("Hero", heroSchema)


Step 2: Creating Some Documents:

The model method above gives us a class, from which we can create objects which will be documented for the collection, which is represented by the class we use. We create two objects from it using the syntax as shown below. Then call the save() method on each object for it to be actually created and stored in the heroes collection,

Javascript




// Creating a collection/model to hold all these documents
const Hero = mongoose.model("Hero", heroSchema)
 
// Creating some heroes/documents for our heroes collection
let hellfire = new Hero({
    name: 'HellFire',
    power: "Manipulate Fire Element",
    rank: "Unknown"
})
hellfire.save()
 
let snowflake = new Hero({
    name: "Snowflake",
    power: "Ice Magic",
    rank: "S"
})
snowflake.save();


Run the following command in the terminal after you have written the above code, to run your application and see the changes happen

node app.js

Now, open the Studio 3T, or the DB viewer you are using, and go to heroesDB database, under it, collections, and double click on heros collection to view it. You can now see the two documents created. Right-click on the first document, select view document, and now copy its _id.

 

 

Step 3: Updating the Document with new Data:

The _id that you copied in the above step, will be used here. Call the findById() method on the Hero class. Pass it the _id that you copied. This will return us a promise, thus we call the then() method on it, and inside it, we have our hero object. Access the properties of this object that you want to change, assign them to their new value, and make sure to use the same data type. Once you are done, call the save() method on this object. Before running the application, comment out the code that creates new documents, otherwise, duplication of documents will happen.

Javascript




// Importing mongoose library and connecting to a MongoDB database
const mongoose = require("mongoose")
 
// Creating a blueprint of each of our document
let heroSchema = mongoose.Schema({
    name: {
        type: String,
        require: true
    },
    power: {
        type: String,
        require: true
    },
    rank: String
})
 
// Creating a collection/model to hold all these documents
let Hero = mongoose.model("Hero", heroSchema)
 
// Updating values of a document
Hero.findById("6396a91c028f4ad3aa1631e9").then((hero)=>{
    hero.rank = "A";
    hero.save();
});


Now run the command to run the application:

node app.js

Right Click on the heros collection, and select refresh. Now if you open this collection by double-clicking it, you can see that the properties have been changed.

 

Things to Keep in Mind: Remember that the save() method returns a promise. Thus, if you doing something after saving your updated document, such as logging something on the console, creating a new object, redirecting to a new webpage, etc, make sure to do it in the then() block, which is chained to the save() method, so that things that need to happen in order, happen in order.

Javascript




// Updating values of a document
Hero.findById("6396a91c028f4ad3aa1631e9").then((hero) => {
    hero.rank = "A"
    hero.save().then(()=>{
        console.log("HellFire was Updated")
    })
})


Full Code:

Javascript




// Importing mongoose library and connecting to a MongoDB database
const mongoose = require("mongoose")
 
// Creating a blueprint of each of our document
let heroSchema = mongoose.Schema({
    name: {
        type: String,
        require: true
    },
    power: {
        type: String,
        require: true
    },
    rank: String
})
 
// creating a collection/model to hold all these documents
let Hero = mongoose.model("Hero", heroSchema)
 
// Creating some heroes/documents for our heroes collection
let hellfire = new Hero({
    name: 'HellFire',
    power: "Manipulate Fire Element",
    rank: "Unknown"
})
hellfire.save()
 
let snowflake = new Hero({
    name: "Snowflake",
    power: "Ice Magic",
    rank: "S"
})
snowflake.save()
 
// Updating values of a document
Hero.findById("6396a91c028f4ad3aa1631e9").then((hero) => {
    hero.rank = "A"
    hero.save().then(() => {
        console.log("HellFire was Updated")
    })
});


Output:

 

Reference: https://mongoosejs.com/docs/documents.html#updating-using-save



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads