分类 MongoDB 下的文章

效果.png
前后端文件NodeMongoose (2).zip
前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch 学习</title>
    <style>
        form{
            display:flex;
            flex-direction:column;
        }
        label{
            margin-bottom:10px;
        }
        input{
            padding:5px;
            margin-bottom:10px;
            border-radius:5px;
            border:1px solid #ccc;
        }
        button{
            padding:5px 10px;
            margin-bottom:10px;
            border-radius:5px;
            border:none;
            background-color:#4CAF50;
            color:#fff;
            cursor:pointer;
            }
    </style>
</head>
<body>
    <form action="#" class="add">
        <label for="id">ID:</label>
        <input type="number" id="id" name="id" required>
    </br>
        <label for="text">Text:</label>
        <input type="text" id="text" name="text" required>
    </br>
        <button type="submit">添加数据</button>
    </form>
    </br>
    <label for="getId">ID:</label>
        <input type="number" id="getId" name="getId" required>
</br>
    <button id="getBtn">获取数据</button>
    <button id="updateBtn">更改数据</button>
    <button id="deleteBtn">删除数据</button>
    <button id="getOneBtn">获取单条数据</button>
    <p id="result"></p>
</body>
<script>
    //get请求
    async function getQuotes(){
        const res = await fetch('http://localhost:3000/quotes')
        const data = await res.json()
        console.log(data)
       document.getElementById('result').innerHTML = data.data.map(item => `<p>${item.text}</p>`).join('')}
    
    //post请求
    async function addQuote(id,text){
        let data = {
            id,
            text
        }
        const res = await fetch('http://localhost:3000/add',{
            method:'POST',
            headers:{
                'Content-Type':'application/json'
            },
            body:JSON.stringify(data)
        })
        const result = await res.json()
        console.log(result)
        }
        
    //put请求
    async function updateQuote(id,text){
        let data = {
            id,
            text
        }
        const res = await fetch('http://localhost:3000/update',{
            method:'PUT',
            headers:{
                'Content-Type':'application/json'
            },
            body:JSON.stringify(data)
        })
        const result = await res.json()
        console.log(result)
    }
    //delete请求
    async function deleteOne(id){
        const res = await fetch(`http://localhost:3000/delete/${id}`,{
            method:'DELETE',
            headers:{
                'Content-Type':'application/json'
            },
            data:JSON.stringify(id)
        })
        const result = await res.json()
        console.log(result)
    }
    //获取单条数据
    async function getQuotesOne(id){
        const res = await fetch(`http://localhost:3000/quotes?id=${id}`)
        const data = await res.json()
        console.log(data)
        document.getElementById('result').innerHTML = `<p>${data.data.text}</p>`
    }
    getQuotes()
</script>
<script>
    document.getElementById('getBtn').addEventListener('click',async()=>{
        await getQuotes()
    })
    document.getElementById('updateBtn').addEventListener('click',async()=>{
        await updateQuote(4,'测试更改数据了')
        getQuotes()
    })
    document.getElementById('deleteBtn').addEventListener('click',async()=>{
        const id = document.getElementById('getId').value
        await deleteOne(id)
        getQuotes()
    })
    document.querySelector('.add').addEventListener('submit',async(e)=>{
        e.preventDefault()
        const id = e.target.elements.id.value
        const text = e.target.elements.text.value
        await addQuote(id,text)
        e.target.reset()
        getQuotes()
    })
    document.getElementById('getOneBtn').addEventListener('click',async()=>{
        const id = document.getElementById('getId').value
        await getQuotesOne(id)
    })
</script>
</html>

数据库操作

import mongoose from 'mongoose';

// 创建Schema和Model
const QuoteSchema = new mongoose.Schema({
    id: { type: Number, unique: true, default: 0, required: true },
    text: { type: String, required: true },
});

const QuoteModel = mongoose.model('Quote', QuoteSchema);

function log(msg) {
    console.log(msg);
}

async function main() {
    try {
        await mongoose.connect('mongodb://admin:admin123@localhost:27017/quotes?authSource=admin');
        log('数据库连接成功');

        const QuoteModel = mongoose.model('Quote', QuoteSchema);
        //判断是否存在初始数据
        const existingQuote = await QuoteModel.findOne({ id: 1 });
        if (!existingQuote) {
            const quote = new QuoteModel({ id: 1, text: 'hello world' });
            await quote.save();
            log('初始数据保存成功');
        } else {
            log('初始数据已存在');
        }
    } catch (err) {
        log('出错了:' + err);
    }



}

// 添加新的内容的异步函数
async function addQuote(id, text) {
    try {
        const Quotes = mongoose.model('Quote');
        //判断是否存在相同id的数据
        const existingQuote = await Quotes.findOne({ id: id });
        if (existingQuote) {
            log('ID已存在,无需添加');
            return false;
        }
        const quote = new Quotes({ id: id, text: text });
        await quote.save();
        log('数据保存成功');
        return true;
    } catch (err) {
        log('添加数据出错:' + err)
    }

}


// 删除指定ID的异步函数
async function deleteQuote(id) {
    try {
        const Quotes = mongoose.model('Quote');
        //判断是否存在指定ID的数据
        const existingQuote = await Quotes.findOne({ id: id })
        if (!existingQuote) {
            log('ID不存在,无需删除');
            return false;
        }
        const result = await Quotes.deleteOne({ id: id });
        if (result.deletedCount === 1) {
            log('数据删除成功');
            return true;
        } else {
            log('数据删除失败');
            return false;
        }
    } catch (err) {
        log('删除数据出错:' + err)
    }

}


// 更新指定ID的异步函数
async function updateQuote(id, text) {
    try {
        const Quotes = mongoose.model('Quote');
        //判断是否存在指定ID的数据
        const existingQuote = await Quotes.findOne({ id: id });
        if (!existingQuote) {
            log('ID不存在,无需更新');
            return false;
        }
        const result = await Quotes.updateOne({ id: id }, { $set: { text: text } });
        if (result.modifiedCount === 1) {
            log('数据更新成功');
            return true;
        } else {
            log('数据更新失败');
            return false;
        }
    } catch (err) {
        log('更新数据出错:' + err)
    }

}

// 查找全部数据的异步函数
async function findQuoteMany() {
    try {
        const Quotes = mongoose.model('Quote');
        const quotes = await Quotes.find().select('id text');
        console.log(quotes)
        return quotes;
    } catch (err) {
        log('查找数据出错:' + err)
    }

}
// 导出包含以上功能的模块
export default {
    addQuote,
    deleteQuote,
    updateQuote,
    findQuoteMany,
}
// 运行main函数
main();


函数处理


import db from './db/mongodb.js';

const sendResponse = (res, status, message, data) => {
    res.status(status).json({
        status: status < 500 ? 0 : 1,
        message,
        data
    })
};
const addQuotes = async (req, res) => {
    const { id, text } = req.body;
    if (!id || !text) {
        return sendResponse(res, 400, "参数错误", []);
    }
    try {
        const result = await db.addQuote(req.body.id, req.body.text);
        if (result) {
            sendResponse(res, 200, "添加成功", [{ id, text }]);
        } else {
            sendResponse(res, 404, "添加失败,id已存在或未更改", []);
        }
    }
    catch (err) {
        sendResponse(res, 500, "服务器错误", []);
    }
}

const deleteQuotes = async (req, res) => {
    const { id } = req.params;
    if (!id) {
        return sendResponse(res, 400, "参数错误", []);
    }
    try {
        const result = await db.deleteQuote(id);
        if (result) {
            sendResponse(res, 200, "删除成功", [{ id }]);
        } else {
            sendResponse(res, 404, "删除失败,id不存在", []);
        }
    } catch (err) {
        sendResponse(res, 500, "服务器错误", []);
    }
}

const updateQuotes = async (req, res) => {
    const { id, text } = req.body;
    if (!id || !text) {
        return sendResponse(res, 400, "参数错误", []);
    }
    try {
        const result = await db.updateQuote(id, text);
        if (result) {
            sendResponse(res, 200, "更新成功", [{ id, text }]);
        } else {
            sendResponse(res, 404, "更新失败,id不存在", []);
        }
    } catch (err) {
        sendResponse(res, 500, "服务器错误", []);
    }
}

const findQuotesMany = async (req, res) => {
    try {
        const result = await db.findQuoteMany();
        if (result && result.length > 0) {
            sendResponse(res, 200, '查询成功', result);
        } else {
            sendResponse(res, 404, '查询失败,数据为空', []);
        }
    } catch (err) {
        sendResponse(res, 500, '服务器错误', []);
    }
};


export default {
    addQuotes,
    deleteQuotes,
    updateQuotes,
    findQuotesMany,
}