How to Update MongoDB Data with Node.js and Mongoose

8/11/2020·3 min read

This blog will show a tutorial about how to update data into MongoDB by using Node.js with Mongoose. Mongoose is the Object Data Modeling library for MongoDB and Node.js. It provides functions for schema, query building, and more. If you don't use Mongoose to access MongoDB with Node.js, then you can use the MongoDB package for Node.js directly. 

Get Start

First, initialize a new npm package, we'll create a new package and new file, and add our code for how to insert data to MongoDB.

npm init -y

Next, let's install the mongoose package, this will be the only package we'll use for this tutorial. 

npm install --save mongoose

Create an index.js, we'll add our code to this file to connect to MongoDB and insert data to the Database.

Connect to the MongoDB

Now, the following is a sample code to connect to MongoDB. Assume you already set up MongoDB at your local and has a database as your-database.

const {connect} = require('mongoose');

connect('mongodb://localhost:27017/your-database')
.then(() => {
    console.info('connect successfully')
})
.catch(() => {
    console.error('connection error');
});

Defined MongoDB Schema

Here, we'll define our collection in MongoDB, the collection name will be my-collection-name.

let localModel = new Schema({
    key: {
        type: String
    },
    value: {
        type: String
    },
    culture: {
        type: String
    }
})

let localSchema = model('localization', localModel, 'my-collection-name');

Update data from MongoDB

Now, this is the final step we'll find data from the collection, then update the data. Following code will first find records by key 'test-key', then update the value field. 

const updateDataAsync = async() => {
    
    let result = await localSchema.find({key: 'test-key'});
    if (result) {
        let updateResult = await localSchema.updateOne({
            _id: result[0]._id
        }, {
            value: 'test3'
        });
        if (updateResult) {
            console.info('update successfully')
        }
    }
}

updateDataAsync();

Conclusion

Now, above is how you can update data from MongoDB by using Node.js with Mongoose.