DEV Community

Pepper.
Pepper.

Posted on • Edited on

Using MongoDB with Node.JS

First, create a new project.

CD into the project folder and run npm init. Follow those steps until you're done.

Run: npm i mongodb. This will install the official MongoDB driver for Node.

Create an index.js, or main.js, depending on your main file when you ran npm init.

Inside there: add this:

const {MongoClient} = require("mongodb");
const mongouri = 'mongodb://your_connection_string';
const client = new MongoClient(mongouri);

client.connect().then(console.log("Connected to MongoDB"));
Enter fullscreen mode Exit fullscreen mode

Congrats, if you run node ., you should see 'Connected to MongoDB'.

Let's create a quick question database by using an asynchronous function. Add this above client.connect().then(console.log("Connected to MongoDB")); and under the constants:

async function createListing(db, collection, data) {
    await client.db(db).collection(collection).insertOne(data);
}
Enter fullscreen mode Exit fullscreen mode

Then, under client.connect(..., put:

createListing('question', 'questions', {
    question: "What's 2+2?",
    answer: 4
});
Enter fullscreen mode Exit fullscreen mode

Go ahead and run node .. If you have access to your database, you should see that listing in the database.

Let's read a listing and compare an answer by creating another asynchronous function. Under the 'createListing' function, add:

async function readListing(db, collection, data) {
    const result = await client.db(db).collection(collection).findOne(data);
    if(result === null || result === undefined) {
        return false;
    }
    return result;
}
Enter fullscreen mode Exit fullscreen mode

Then, let's remove the lines where we created our listing, and we will replace it with:

let guess = 4;
const res = await readListing('question', 'questions', {
    answer: guess
});
if(res === false) {
    console.log("Oops, you got it wrong.");
} else {
    console.log("Yay! You got it right!");
}
Enter fullscreen mode Exit fullscreen mode

And now, we will run node ., it should output: "Yay! You got it right!"

Congratulations! You've just created and read data from a database!

To the beginners: Keep learning. You never know what you can accomplish if you keep putting your all into it. This tutorial has just showed you how to use one of the BEST databases out there, very easily. So go and do what we all beginners should do, keep learning, and keep attempting new things. Good luck!

Top comments (6)

Collapse
 
juliannicholls profile image
Julian Nicholls

Allowing for the fact that I haven't tried this code...

Shouldn't the

const res = readListing('question', 'questions', {
    answer: guess
});
Enter fullscreen mode Exit fullscreen mode

be

const res = await readListing('question', 'questions', {
    answer: guess
});
Enter fullscreen mode Exit fullscreen mode

because readListing() is an async function.

Collapse
 
peppermints profile image
Pepper.

Yes haha, I completely forgot about this. Thank you!

Collapse
 
logicmirror profile image
LogicMirror

For me it didn't work with the async but did once I took it out.

Thread Thread
 
peppermints profile image
Pepper.

It should work, and it is supposed to be async- but if it works for you then that'd fine! Enjoy :)

Collapse
 
chukwuebukakennedy profile image
Kennedy

Nice Post!
I tried implementing this to my simple test in node.js and I get the ENOTFOUND Error.
Any idea?

Collapse
 
peppermints profile image
Pepper.

Pretty sure this is an uninstalled module error, if I'm incorrect post the error here and I can tell you the problem. But if it's what I think it is: run

npm install mongodb