Cara menggunakan mongodb localhost 27017

I can't connect to the local mongodb server running on localhost:27017 from my express application. I'm pretty sure that I haven't done anything wrong in the code I wrote as I've copied it from a tutorial. The code worked fine on that tutorial. And I've also made sure that the mongodb service is running. I've already created a database called "blog" from mongosh shell and inserted some data to a collection called "authors" on it. I've also installed the MongoDB Node Driver using "npm install mongodb" command. But whenever I try to run npm start, this error shows up and I can't run my application thereafter.

E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306
                const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
                                     ^

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306:38)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 195900556,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
            at Socket. (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
            at Object.onceWrapper (node:events:642:26)
            at Socket.emit (node:events:527:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          [Symbol(errorLabels)]: Set(0) {}
        }
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

Node.js v18.2.0
[nodemon] app crashed - waiting for file changes before starting...

This is the code I wrote on database.js to create the connection to the local mongodb server.

const mongodb = require("mongodb");

const MongoClient = mongodb.MongoClient;

let database;

async function connect() {
  const client = await MongoClient.connect("mongodb://localhost:27017");
  database = client.db("blog");
}

function getDb() {
  if (!database) {
    throw { message: "Database connection not established!" };
  }
  return database;
}

module.exports = {
  connectToDatabase: connect,
  getDb: getDb,
};

This is the code I wrote on app.js to connect the database to it and run the application.

const path = require("path");

const express = require("express");

const blogRoutes = require("./routes/blog");
const db = require("./data/database");

const app = express();

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));

app.use(blogRoutes);

app.use(function (error, req, res, next) {
  console.log(error);
  res.status(500).render("500");
});

db.connectToDatabase().then(function () {
  app.listen(3000);
});

I always use MongoDB as a database when I work on an app. And I like to connect to a database on my computer because it speeds up dev and test-related work.

Today, I want to share how to create and connect to a local MongoDB Database.

Installing MongoDB

You need to install MongoDB on your computer before you can connect to it. You can install MongoDB by following these instructions (Mac and Windows).

Once you have completed the installation process, try typing

mongod
7 into your command line. You should get a response similar to the following:

mongo --version
Cara menggunakan mongodb localhost 27017

Starting MongoDB

You can start MongoDB on your computer with the

mongod
8 command.

mongod
Cara menggunakan mongodb localhost 27017

Keep the

mongod
8 window running when you want to work with your local MongoDB. MongoDB stops when you close the window.

Brief overview of how MongoDB works

MongoDB lets you store things (called documents) inside databases. Each database contains multiple collections.

To make it easier to understand, you can think of MongoDB as a building. It contains many rooms.

Each room is a database. Each database is responsible for storing information about one application. You can store as much information as you want.

You have an unlimited supply of boxes in each room. Each box is a collection. Each collection can only contain one type of data.

For example, one collection can be used for books, one collection for users, one collection for toys, and so on.

Adding items to a database

One way to add items to a MongoDB database is through the Mongo Shell. To open up the Mongo Shell, you open another command line window and run

mongo
0.

mongo
Cara menggunakan mongodb localhost 27017

Note: Make sure you keep the

mongod
8 window open! You won’t be able to interact with the Mongo Shell if you close the
mongod
8 window.

First, we need a database to work with. You can see the currently selected database with the

mongo
3 command. (By default, you should be on the
mongo
4 database).

> db

Note: The

mongo
5 in the code above signifies the Mongo Shell. You don’t need to type
mongo
5. It is not part of the command.

Cara menggunakan mongodb localhost 27017

For this article, we’ll create a database called

mongo
7. You can use the
mongo
8 command to create and switch to a new database.

> use game-of-thrones
Cara menggunakan mongodb localhost 27017

We’re going to add a character into the

mongo
7. Here, we need to put the character into a collection. We’ll use
> db
0 as the name of the collection.

To add an item to a collection, you can pass a JavaScript object into

> db
1.

db.characters.insertOne({ name: 'Jon Snow' })
Cara menggunakan mongodb localhost 27017

Let’s add one character into the database before we continue.

db.characters.insertOne({ name: 'Arya Stark' })
Cara menggunakan mongodb localhost 27017

You can see the characters we’ve added by using the

> db
2 command. (
> db
3).

db.characters.find()
Cara menggunakan mongodb localhost 27017

This is all you need to know about the Mongo Shell for now.

Accessing MongoDB with MongoDB Compass

MongoDB Compass gives you another way to access MongoDB. It’s an app that makes checking (and editing) databases easier if you’re not a fan of the command line.

To use MongoDB Compass, you have to install it first. You can download and install MongoDB Compass from the this page.

When you open MongoDB Compass, you’ll see a screen that looks like this:

Cara menggunakan mongodb localhost 27017

To connect to your local MongoDB, you set

> db
4 to
> db
5 and
> db
6 to
> db
7. These values are the default for all local MongoDB connections (unless you changed them).

Cara menggunakan mongodb localhost 27017

Press connect, and you should see the databases in your local MongoDB. Here, you should be able to see

mongo
7 (the database we created for this tutorial).

Cara menggunakan mongodb localhost 27017

If you click on

mongo
7, you’ll see a
> db
0 collection.

Cara menggunakan mongodb localhost 27017

And if you click on

> db
0, you’ll see the two characters we created in the earlier section.

Cara menggunakan mongodb localhost 27017

This is how you can use MongoDB Compass to connect to a MongoDB that’s running on your own computer.

Connecting to MongoDB with a Node server

When we build applications, we connect to MongoDB through our applications (not through Mongo Shell nor MongoDB Compass).

To connect to MongoDB, we need to use the mongodb package. Alternatively, you can also use Mongoose.

(By the way, I prefer using Mongoose over the MongoDB native driver. I’ll share why in a future article).

Connecting with MongoDB native driver

First you have to install and require the mongodb package.

npm install mongodb --save
const MongoClient = require('mongodb').MongoClient

You can connect to your local MongoDB with this url:

mongod
0

With the Mongo Client, you need to specify the database you’re using after you connect to MongoDB. Here’s what it looks like:

mongod
1
Cara menggunakan mongodb localhost 27017

Connecting with Mongoose

To connect with Mongoose, you need to download and require

> use game-of-thrones
2.

mongod
2
mongod
3

When you use Mongoose, the connection

> use game-of-thrones
3 should include the database you’re connecting to:

mongod
4

You can connect to MongoDB with the

> use game-of-thrones
4 method:

mongod
5

Here’s how you can check whether the connection succeeds.

mongod
6
Cara menggunakan mongodb localhost 27017

If you enjoyed this article, please support me by sharing this article Twitter or buying me a coffee 😉. If you spot a typo, I’d appreciate if you can correct it on GitHub. Thank you!

MongoDB menggunakan bahasa apa?

MongoDB sendiri ditulis dengan bahasa C++ dan telah tersedia untuk berbagai jenis bahasa pemrograman. Fitur utama dari mongoDB antara lain: model document-oriented storage.

MongoDB digunakan untuk apa?

3. Cocok Untuk Menampung Data yang Bervariasi Dynamic schema membuat MongoDB cocok untuk menampung data yang bervariasi baik digunakan untuk menyimpan data yang terstruktur ataupun yang tidak terstruktur.

Apakah MongoDB NoSQL?

Mongo DB adalah salah satu jenis database yang menggunakan konsep NoSQL berbasis dokumen. MongoDB ini merupakan basis data NoSQL yang gak menyimpan data dalam tabel, akan tetapi menggunakan dokumen terstruktur layaknya JSON (JavaScript Object Notation).

Mengapa MongoDB disebut database berorientasi dokumen?

Berorientasi pada dokumen-Karena MongoDB adalah database tipe NoSQL, alih-alih memiliki data dalam format tipe relasional, MongoDB menyimpan data dalam dokumen. Ini membuat MongoDB sangat fleksibel dan mudah beradaptasi dengan situasi dan persyaratan dunia bisnis nyata.