DEV Community

Cover image for Install MongoDB In Windows 10. After Then Using Node.Js Connect MongoDB
Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

Install MongoDB In Windows 10. After Then Using Node.Js Connect MongoDB

Now I share with everyone how we can Connect MongoDB with Node.JS. Recently I had to redo a small project, with Connect MongoDB + NodeJS + Vue (combined with Vuex) to manage the state of the data.

It's been a while since I've used MongoDB. It's been so confusing trying to find and install it. But it's okay, as for the breath, we'll find it, kaka

INSTALL MONGODB IN WINDOWS 10
The first thing is to find and install MongoDB . Please go here and download and install: https://www.mongodb.com/try/download/community

Install MongoDB In Windows 10. After Then Using Node.Js Connect MongoDB - hoanguyenit.com

When you finish installing, you will be given the above, you will get a connection string like this mongodb://localhost:27017 , Click on "Connect" to continue creating the database

Install MongoDB In Windows 10. After Then Using Node.Js Connect MongoDB - hoanguyenit.com

The only thing left is to create a Nodejs project and Connect MongoDB

SETUP NODEJS CONNECT MONGODB

Create a Nodejs project . You need to install the Node.js library on your computer

npm init
Enter fullscreen mode Exit fullscreen mode

Okay, you can copy your package and json to install quickly and easily, otherwise you can install each library into

{
  "name": "nodejs-react",
  "version": "1.0.0",
  "description": "nodejs react",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "react"
  ],
  "author": "hoanguyenit",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^6.2.0",
    "mongoose": "^6.0.9",
    "sqlite3": "^5.0.2",
    "uid": "^2.0.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.13"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then open Command Line and run npm install command

npm install
Enter fullscreen mode Exit fullscreen mode

So you have installed all the libraries such as jsonwebtoken , cors , mongodb , mongoose ,... whichever one you use, just import it into the file.

After you have a Nodejs project , create a file index.js at the same level as the project

const http = require("http");
const app = require("./app");
const server = http.createServer(app);

const { API_PORT } = process.env;
const port = process.env.PORT || API_PORT;

// server listening 
server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Next create app.js as follows:

require("dotenv").config();
const express = require("express");
const jwt = require("jsonwebtoken");
const { MongoClient } = require('mongodb');
var cors = require('cors');
const router = express.Router();
const app = express();
app.use(cors());
app.use(express.json());

// Connection URL
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'shopbanhang';
let connectDB;

// Kết nối đến MongoDB
async function connectToMongoDB() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');

    // Lưu trữ đối tượng cơ sở dữ liệu để sử dụng toàn cục
    connectDB = client.db("shopbanhang");
  } catch (error) {
    console.error('Error connecting to MongoDB:', error);
  }
}

connectToMongoDB().catch(console.dir);

//lấy tất cả danh sách hang hoa
router.get("/getItems", async (req, res) => {
  try {
    const collection = connectDB.collection("HangHoa");

    // Sử dụng phương thức find() để lấy tất cả các documents trong collection
    const hanghoas = await collection.find({}).toArray();
    // Log tất cả users

    res.status(200).json({"success":1,"ListsHangHoa":hanghoas});
  } catch (error) {
    console.error('Error getting all hanghoas:', error);
  }
})


app.use('/', router);
module.exports = app;
Enter fullscreen mode Exit fullscreen mode

Above we need to import the mongodb library

const { MongoClient } = require('mongodb');

Enter fullscreen mode Exit fullscreen mode

Next is when we call connect to MongoDB

// Connection URL
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'shopbanhang';
let connectDB;

// Kết nối đến MongoDB
async function connectToMongoDB() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');

    // Lưu trữ đối tượng cơ sở dữ liệu để sử dụng toàn cục
    connectDB = client.db("shopbanhang");
  } catch (error) {
    console.error('Error connecting to MongoDB:', error);
  }
}
connectToMongoDB().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

You see I'm using the address 127.0.0.1 , instead of localhost, right? In case you cannot use the connect string mongodb://localhost:27017 , please use the ip address : mongodb://127.0.0.1:27017

That's it, you write the add, edit, delete commands, try it out

Below is the code I use Nodejs+MongoDB . Combined with Json Web Token, you can see this article -> : JWT(Json Web Token) In Node.Js

Okay, we can run it

npm run dev
//or
node index.js
Enter fullscreen mode Exit fullscreen mode

The post : Install MongoDB In Windows 10. After Then Using Node.Js Connect MongoDB

Top comments (0)