mongoose
Web/Node.js

mongoose

mongoose?

mongoose는 mongoDB의 데이터를 쉽게 관리해주는 패키지다. 공식 문서에서 mongoose를 ODM(Object Document Mapping)으로 소개하고 있으며, 객체와 문서를 1:1로 매칭된다. 여기서 Obect는 JS 객체를 뜻하고, Document는 mongoDB 문서(데이터)를 의미한다.

Document를 조회할 때 JS Object로 바꿔주는 역할

 

mongoose 설치 및 Atlas 연결

npm install mongoose

위에서 mongoDB와 연결을 위해 복사한 코드를 ./bin/www 파일의 mongoose.connect에 붙여넣으면 된다.

/* ./bin/www */

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('first-project:server');
var http = require('http');

// 비밀번호 노출 방지 목적으로 config 파일에서 pw 불러오기
const dbConfig = require("../config/dbConfig.json");

/**
 * Get port from environment and store in Express.
 */

// mongoose 연결
const mongoose = require('mongoose');
const db = mongoose.connection;
db.on("error", console.error);
db.once("open", () => {
  console.log("Connected to mongodb server!");
});

mongoose.connect(
  // 비밀번호 노출 방지를 위해 config 파일에서 pw를 불러움
  `mongodb+srv://${dbConfig.id}:${dbConfig.pw}@cluster0.txct3.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`,
  {useNewUrlParser : true, useUnifiedTopology: true }
);

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

정보보호를 위해 id 및 pw는 따로 외부의 json 파일에 정의해준다.

/* ./config/dbConfig.json */

{
    "name" : "first-project",
    "id" : <ID>,
    "pw" : <PW>
}

파일을 저장하고 npm을 재실행하면 www파일에서 정의한대로 "Connected to mongodb server!"가 출력된다.

'Web > Node.js' 카테고리의 다른 글

mongoose schema  (0) 2022.01.10
express-session  (0) 2022.01.04
미들웨어  (0) 2022.01.04
express - HTTP method  (0) 2022.01.04
Routing  (0) 2022.01.04