상세 컨텐츠

본문 제목

node mongoose

자바스크립트

by e7e 2023. 4. 16. 00:01

본문

==>

주의 접속 URL문자열에 localhost가 안될 때 있음 => 127.0.0.1롱!!!

 

import express from 'express';
import mongoose from 'mongoose';
import serveIndex from 'serve-index';


const app = express();
app.set("port", 272);


//app.use(express.static("public"),serveIndex("public",{hidden:true}));// 요거 있으면 get밖에 안됨!!,option???
app.use(express.static("public"));
app.use(express.urlencoded({ extended:true}));
app.use(express.json());

//접속mongodb://localhost:27017
const MONGO_URI = "mongodb://127.0.0.1:27017/simple-chat";
mongoose
  .connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Successfully connected to mongodb'))
  .catch(e => console.error(e));

//초간단 Model
const Friend = mongoose.model('Friend',{id:Number, name: String, message: String});


//R
app.get('/friends',(req,res)=>{
    console.log("Read");
    Friend.find({}).then((friends)=>{
        console.log("msgs: " , friends)
        res.send(friends);
    }).catch(err=>{
        console.error(err);
    })
});

//R
app.get('/friends/:fid',(req,res)=>{
    console.log("Read");
    Friend.findOne({id:req.params.fid})
    .then((friend)=>{
        console.log("friend: " , friend);
        res.send(friend);
    }).catch(err=>{
        console.error(err);
    })
});

//C
app.post('/friends',(req,res)=>{
    console.log("Create",req.body);
    Friend.create(req.body)
    .then(friend => res.send(friend))
    .catch(err => {
        console.log(err);
        res.status(err500).send(err)
    });

    /*
    const friend = new Friend(req.body);
    console.log("friend:",msg);
    friend.save().then(()=>{
            console.log('Friend saved');
            res.sendStatus(200);
        }).catch(err => {
            res.sendStatus(500);
        })
    */
});


//U
app.put('/friends',(req,res)=>{
    console.log("Update");
    Friend.findOneAndUpdate({id:req.body.id},req.body,{ new:true})
    .then((friend)=>{
        console.log("friend: ", friend)
        res.send(friend);
    }).catch(err=>{
        res.status(500).send(err);
    })
});

//D
app.delete('/friends',(req,res)=>{
    console.log("Delete");
    Friend.deleteOne({id:req.body.id}).then(()=>{
        res.sendStatus(200);
    }).catch(err=>{
        res.status(500).send(err);
    })
});


app.listen(app.get('port'),()=>{
    console.log(`listening on ${app.get('port')}`);
})

'자바스크립트' 카테고리의 다른 글

fancytree  (0) 2023.05.09
visual studio code emmit 단축키  (0) 2023.04.18
리액트(react)  (0) 2023.02.06
JSTREE 간단 사용법  (10) 2022.12.05
iframe 사이즈 조절  (0) 2022.10.20

관련글 더보기