mongoDb 기본데이터 명령문

So Vidi·2023년 11월 1일

Server

목록 보기
1/4

MongoDB

npm i mongodb

내 키

본인 데이터베이스 공유 키, 자세한 사항은 참조 바람

비번

monboDB 사이트에서 항상 새로 갱신하여 복사된 값을 저장하고 있어야 함.

설정코드

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

const url = 'mongodb+srv://lim132445:zCnCDyeTGM7toUhV@sovidi.v53i9gi.mongodb.net/?retryWrites=true&w=majority';
const client = new MongoClient(url);
const dbName = 'test';

let collection;
const dbConnect = async () => {
    await client.connect();
    const db = client.db("test")
    collection = db.collection("members")
    console.log("mongodb 접속성공")
}

get

app.get('/api', async function (req, res) {
    let data = await collection.find().toArray();
    // console.log(data);
    res.send(data);
})
db.members.find({ "id": qData.id, "password": qData.password })

추가로 특정 값을 추적해서 불러와야 할 경우, && 는 없고 콤마만 사용하면 된다.

post

app.post(`/api/insert`, async function(req, res) {
    await collection.insertOne(req.body);
    const dataGet = await collection.find().toArray();
    res.send(dataGet)
})

테이블에 따로 추가할 사항 없이 객체 key 값으로 테이블 자동 추가하여 들어감

delete

app.delete(`/api/delete`, async function(req, res) {
    let qData = req.query;
    // 보내는 단에서 axios.delete(`/api/delete?date=${date})
    await collection.deleteOne({date: Number(qData.date)});
    const dataGet = await collection.find().toArray();
    res.send(dataGet)
})

put

app.put(`/api/update`, async function (req, res) {
    const {date, id} = req.query;
    const {count} = req.body;
    await collection.updateOne({date: Number(date), id: id}, {$set: {count: count}})
    const result = await collection.find().toArray();
    res.send(result)
})
profile
먹을거 좋아하는데 마른 개발자

0개의 댓글