How to Update MongoDB Data with Node.js and Mongoose

2020/08/112 min read
bookmark this

Table of Contents

  1. Introduction
  2. Get Started
  3. Connect to MongoDB
  4. Define MongoDB Schema
  5. Update Data in MongoDB
  6. Conclusion

Introduction

This blog will show a tutorial about how to update data in 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 Started

First, initialize a new npm package. We'll create a new package and a new file, and add our code for how to update data in 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 file. We'll add our code to this file to connect to MongoDB and update data in the database.

Connect to MongoDB

Now, the following is sample code to connect to MongoDB. Assume you already have MongoDB set up on your local machine and have a database named your-database.

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

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

Define 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 in MongoDB

Now, this is the final step. We'll find data from the collection, then update the data. The 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

The above is how you can update data in MongoDB by using Node.js with Mongoose.