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

2020/9/112 min read
bookmark this
Responsive image

This blog will show a tutorial about how to find 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');

Find data from MongoDB

Now, this is the final step we'll find data from this collection after this code had run it should return a list of result match the key is 'test-key' from 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 do the following query.

const getOneAsync = async() => {

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

getOneAsync();

If you want to find the one then update it, you can try the following code. It'll find then update 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.