- JS에서 MongoDB 함수 간편하게 사용하기2024년 12월 29일
- wngnl05
- 작성자
- 2024.12.29.:26
const mongoose = require("mongoose"); require("dotenv").config(); // MongoDB 연결 설정 const { mongoHost, mongoPw, mongoUser, mongoDB } = process.env; const mongoURI = `mongodb+srv://${mongoUser}:${encodeURIComponent(mongoPw)}@${mongoHost}${mongoDB}?retryWrites=true&w=majority`; // MongoDB 연결 mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log("MongoDB 연결 성공")) .catch(err => console.log("MongoDB 연결 실패:", err)); // MongoDB 명령 실행 함수 async function mongo(command, table, params) { if (!command || !table || !params) { return {} } try { const collection = mongoose.connection.collection(table); switch (command.toUpperCase()) { case "SELECT": return await collection.find(params).toArray(); case "INSERT": return await collection.insertOne(params); case "UPDATE": const { filter, update } = params; if(!filter || !update){ return {} } return await collection.updateMany(filter, { $set: update }); case "DELETE": return await collection.deleteMany(params); default: return {} } } catch (error) { console.error(`MongoDB 명령 실행 중 오류: ${error.message}`); return {} } } module.exports = { mongo };
SELECT 요청 // userEmail 찾기
const result = await mongo("SELECT", tableName, {userEmail: userEmail});
INSERT 요청
await mongo("INSERT", "tabOrder", {userEmail: "", userPassword: ""});
UPDATE 요청
const result = await mongo("UPDATE", tableName, { filter: { userEmail: "" }, update: { userPassword: "" } });
DELETE 요청
const result = await mongo("DELETE", tableName, { userEmail: "" });
'Backend' 카테고리의 다른 글
express 에서 dynamoDB 사용하기 (0) 2025.01.07 다음글이전글이전 글이 없습니다.댓글
스킨 업데이트 안내
현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)