본문 바로가기
창고 3/[Dev] My Readme

몽고 DB 기초 1

by 부엉이의 정보 창고 2022. 1. 4.
728x90

MongoDB is a NO-SQL database that stores JSON documents. Mongoose is a npm package used to control MongoDB with Javascript, creating schemas.

  • SQL : saving all data across tables
  • NO-SQL : saving all data within one record

MongoDB has a merit combinated with Javascript that its format is JSON, which is Javascript Object Notation.

Web - Server - Database

  • Web client : HTML, CSS, Javascript
  • Web server : Node.js, Mongoose(npm package)
  • Database : JSON

Installation

Deployment with MongoDB can be served with

  • Atlas : MongoDB as a service
  • On-premises : Local MongoDB => install MongoDB Compass
  • Mobile & Edge : Realm mobile database. Lightweight data storage for mobile and edge

Connection

  1. Create an account in MongoDB website
  2. Choose a plan : 1) serverless 2) dedicated 3) shared(free, 1 per account)
  3. Set database username and password, which will be used in Mongoose.
  4. Set other configurations for the MongoDB, like IP Access List. One of the common reasons of DB connection failure is not to include your IP address.
  5. Get your MongoDB Atlas URI and set environment variables.
  6. Require Mongoose/Express in your Javascript file and connect database like below.
// case 1 : using process.env to import MONGO_URI
const mongoose = require('mongoose')
const MONGO_URI = process.env['MONGO_URI'] // In .env file, MONGO_URI="your uri"

mongoose.connect(MONGO_URI, {})
        .then(()=>{ console.log("MongoDB connected") })
        .catch((err)=>{ console.log(err) })

// case 2 : using modules to import MONGO_URI
module.exports = { MONGO_URI : "your uri" } // file name : key.js
require('./key')

mongoose.connect(MONGO_URI, {})
        .then(()=>{ console.log("MongoDB connected") })
        .catch((err)=>{ console.log(err) })
728x90

댓글


loading