How to update record without objectID in mongoose?
Last Updated :
14 Dec, 2023
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
- Using FindOneandUpdate() method
- Using FindOne and FindByIdandUpdate Method
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.
Javascript
const mongoose = require( 'mongoose' );
const setup = async () => {
.then(console.log( 'Connected to MongoDB' )). catch (error =>
console.error( 'Failed to connect to MongoDB:' , error));
const userSchema = new mongoose.Schema({
email: { type: String, unique: true },
name: String,
age: Number,
});
const User = mongoose.model( 'User' , userSchema);
const findUserAndUpdateAge = async () => {
try {
const user = await User.findOneAndUpdate({ email: 'example@example.com' },
{ age: 30 },
{ new : true }
);
console.log(user, "User Updated" );
} catch (err) {
console.log(err);
}
};
await findUserAndUpdateAge();
};
setup();
|
Javascript
[{
"_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
Javascript
const mongoose = require( 'mongoose' );
const setup = async () => {
console.error( 'Failed to connect to MongoDB:' , error));
const userSchema = new mongoose.Schema({
email: { type: String, unique: true },
name: String,
age: Number,
});
const User = mongoose.model( 'User' , userSchema);
const findUserAndUpdateAge = async () => {
try {
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);
}
};
await findUserAndUpdateAge();
};
setup();
|
Step to run the application: To run this file you need to run the following command.
node index.js
Output:
Share your thoughts in the comments
Please Login to comment...