How to Find Record from MongoDB with Node.js and Mongoose

2020/09/112 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Getting Started
  3. Connect to MongoDB
  4. Define the MongoDB Schema
  5. Find Data from MongoDB
  6. Conclusion

Introduction

This blog shows a tutorial on how to find data from 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.

Getting Started

First, initialize a new npm package. We'll create a new package and a new file, and add our code for how to find data from 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 query data from the database.

Connect to MongoDB

Now, the following is a sample code to connect to MongoDB. Assume you already have MongoDB set up locally and have a database called your-database.

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

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

Define the 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');

Find Data from MongoDB

Now, this is the final step. We'll find data from this collection. After this code runs, it should return a list of results matching the key test-key from the collection my-collection-name.

const getDataAsync = async() => {

    let result = await localSchema.find({key: 'test-key'});

}

getDataAsync();

If you only expect to return one record, you can use the following query.

const getOneAsync = async() => {

    let result = await localSchema.findOne({key: 'test-key'});
    console.info(result);
}

getOneAsync();

If you want to find a record and then update it, you can try the following code. It will find the record and then update it with the new value.

const getAndModifyAsync = async() => {

    let result = await localSchema.findOneAndUpdate({key: 'test-key'}, {
        value: "my new value"
    })
}

getAndModifyAsync();

Conclusion

Above is how you can get data from MongoDB by using Node.js with Mongoose.