数据库操作

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,
}

标签: nodejs, mongoose, mongodb, curd

已有 4 条评论

  1. 作者对主题的挖掘深入骨髓,展现了非凡的洞察力和理解力。

  2. ?实用类评语?

  3. 新车即将上线 真正的项目,期待你的参与

  4. 2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
    新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
    新车首发,新的一年,只带想赚米的人coinsrore.com
    新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
    做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
    新车上路,只带前10个人coinsrore.com
    新盘首开 新盘首开 征召客户!!!coinsrore.com
    新项目准备上线,寻找志同道合的合作伙伴coinsrore.com
    新车即将上线 真正的项目,期待你的参与coinsrore.com
    新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
    新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com

添加新评论