How to useFindOneAndUpdate Methods to update the records in Mongoose
Example: Add this code in index.js file and insert json file in the MongoDB collection named Users.
Javascript
//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(); |
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:
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.