Open In App

How to update record without objectID in mongoose?

Mongoose is an ODM(Object Data Library) for MongoDB in Node JS that helps to write schema, validation and business logic in a simple way without the hassle of native MongoDB boilerplate.

Prerequisites

Approach to update record without objectID:

There are two ways we can update a record in MongoDB using Mongoose



Steps to Create Node Application and Installation of mongoose module:

Step 1: Open the terminal in the folder you want and enter the following command:

npm init -y

Step 2: Your node project will be ready. create the index.js file using the command below



touch index.js

Step 3: You can install this package by using this command.

npm install mongoose

Step 4: Connection to MongoDB using mongoose:

In the index.js file import the mongoose module and use the connect function to connect the database

 mongoose.connect('mongodb://127.0.0.1:27017/GFG').then(console.log('Connected to MongoDB')

Here is the connection string where i have used 127.0.0.1 you can also use localhost, next is the port no which is 27017 and then is the name of the database where you want to create your collections

Folder Structure:

Folder structure

The updated dependencies in package.json file will look like:

"dependencies": {
    "mongoose": "^8.0.3"
}

Approach 1: Using FindOneAndUpdate Methods to update the records

Example: Add this code in index.js file and insert json file in the MongoDB collection named Users.




//index.js
 
const mongoose = require('mongoose');
 
const setup = async () => {
    await mongoose.connect('mongodb://127.0.0.1:27017/GFG')
                  .then(console.log('Connected to MongoDB')).catch(error =>
                           console.error('Failed to connect to MongoDB:', error));
 
 
    // Define the schema
    const userSchema = new mongoose.Schema({
        email: { type: String, unique: true },
        name: String,
        age: Number,
    });
 
    // Create a model based on the schema
    const User = mongoose.model('User', userSchema);
 
    // Find a user and update their age
    const findUserAndUpdateAge = async () => {
        try {
            // Use await to get the result of findOneAndUpdate
            const user = await User.findOneAndUpdate({ email: 'example@example.com' },
                                                     { age: 30 },
                                                     { new: true }
                                                    );
            console.log(user, "User Updated");
        } catch (err) {
            console.log(err);
        }
    };
 
    // Call the update function
    await findUserAndUpdateAge();
 
};
 
// Call the setup function to execute the code
setup();




[{
    "_id": {
        "$oid": "65767ccc6952cf734319b873"
    },
    "email": "example@example.com",
    "name": "John Doe",
    "age": 25,
    "__v": 0
},
{
    "_id": {
        "$oid": "65767cea46c027123509beef"
    },
    "email": "example2@example.com",
    "name": "John Doe",
    "age": 25,
    "__v": 0
},
{
    "_id": {
        "$oid": "65767cf53ad13463a619c8c9"
    },
    "email": "exampl32@example.com",
    "name": "John Doe",
    "age": 25,
    "__v": 0
}]

MongoDB inserted data:

Steps to run the project: Open the terminal and write the following command

node index.js

Output:

Approach 2: Using FindOne and FindByIdandUpdate Method to update the records




//index.js
 
const mongoose = require('mongoose');
 
const setup = async () => {
    await mongoose.connect('mongodb://127.0.0.1:27017/GFG').then(console.log('Connected to MongoDB')).catch(error =>
        console.error('Failed to connect to MongoDB:', error));
 
 
    // Define the schema
    const userSchema = new mongoose.Schema({
        email: { type: String, unique: true },
        name: String,
        age: Number,
    });
 
    // Create a model based on the schema
    const User = mongoose.model('User', userSchema);
 
    // Find a user and update their age
    const findUserAndUpdateAge = async () => {
        try {
            // Use await to get the result of findOneAndUpdate
            const user = await User.findOne({ email: 'example@example.com' });
            const updatedUser = await User.findByIdAndUpdate(user._id, { age: 30 }, { new: true });
            console.log(updatedUser, "User Updated");
        } catch (err) {
            console.log(err);
        }
    };
 
    // Call the update function
    await findUserAndUpdateAge();
};
 
// Call the setup function to execute the code
setup();

Step to run the application: To run this file you need to run the following command.

node index.js

Output:


Article Tags :