Node.js 的学习(四)分别连接MongoDB与MySQL数据库,实现增删查改功能
阅读原文时间:2023年07月08日阅读:1

MongoDB 对许多平台都提供驱动可以访问数据库,如C#、Java、Node.js等。

1.1、安装MongoDB访问驱动

命令如下:

全局安装驱动:npm install mongodb -g

在当前项目中引入:npm install mongodb --save

1.2、连接数据库

const { MongoClient } = require("mongodb"); //导入依赖对象mongo客户端

let url="mongodb://127.0.0.1:27017"; //数据库连接字符串

let client=new MongoClient(url); //实例化一个mongo客户端

async function run(){
try{
await client.connect(); //连接
await client.db("nfit").command({ping:1}); //向数据库nfit发送命令
console.log("连接数据库成功!");
}
finally{
await client.close();
}
}

run().catch(console.log);

1.3、添加数据

const { MongoClient } = require("mongodb"); //依赖MongoClient

let client=new MongoClient("mongodb://127.0.0.1:27017"); //实例化一个客户端

async function run(){
try{
let db=await client.db("nfit"); //获取数据库
let students=await db.collection("students"); //获取集合,表
let doc={id:202201,name:"tom",age:19}; //将添加的数据对象
let result=await students.insertOne(doc); //执行向数据库中添加数据并等待响应结果
console.log(result);
}
finally{
await client.close(); //关闭数据库
}
}

run().catch(console.log);

1.4、添加多条数据

const { MongoClient } = require("mongodb"); //依赖MongoClient

let client=new MongoClient("mongodb://127.0.0.1:27017"); //实例化一个客户端

async function run(){
try{
let db=await client.db("nfit"); //获取数据库
let students=await db.collection("students"); //获取集合,表
let docs=[{id:202202,name:"rose",age:17},{id:202203,name:"mark",age:18}]; //将添加的数据对象
let result=await students.insertMany(docs); //执行向数据库中添加数据并等待响应结果
console.log(result);
}
finally{
await client.close(); //关闭数据库
}
}

run().catch(console.log);

1.5、修改数据

const { MongoClient } = require("mongodb");
let client=new MongoClient("mongodb://127.0.0.1:27017");

async function run(){
try{
let db=await client.db("nfit"); //获取数据库
let students=await db.collection("students"); //获取集合
let filter={id:202201}; //要更新的数据的过滤条件
let result=await students.updateOne(filter,{$set:{name:"汤姆"}}); //执行更新单条数据
console.log(result);
}
finally{
await client.close(); //关闭
}
}

run().catch(console.log);

1.6、查询数据

1.6.1、查询单条记录

const { MongoClient } = require("mongodb");
let client=new MongoClient("mongodb://127.0.0.1:27017");

async function run(){
try{
let db=await client.db("nfit"); //获取数据库
let students=await db.collection("students"); //获取集合

    let filter={id:202201};  //过滤条件  
    let obj=await students.findOne(filter);  //根据过滤条件查找单条数据  
    console.log(obj);  
}  
finally{  
    await client.close();  //关闭  
}  

}

run().catch(console.log);

1.6.2、查询多条记录

const { MongoClient } = require("mongodb");
let client=new MongoClient("mongodb://127.0.0.1:27017");

async function run(){
try{
let db=await client.db("nfit"); //获取数据库
let students=await db.collection("students"); //获取集合

    let query={id:{$gte:202201}};  //查询条件是id大于等于202201  
    let cursor=await students.find(query);  //执行查询并返回游标对象

    let result=\[\];  //学生数组,返回包装用

    await cursor.forEach(data=>result.push(data));  //遍历游标,取出数据

    console.log(result);  
}  
finally{  
    await client.close();  //关闭  
}  

}

run().catch(console.log);

1.7、删除数据

const { MongoClient } = require("mongodb");
let client=new MongoClient("mongodb://127.0.0.1:27017");

async function run(){
try{
let db=await client.db("nfit"); //获取数据库
let students=await db.collection("students"); //获取集合
let filter={id:202201}; //要删除的数据的过滤条件
let result= await students.deleteOne(filter); //执行删除
console.log(result);
}
finally{
await client.close(); //关闭
}
}

run().catch(console.log);

1.8、连接MongoDB数据库,实现curd、图片上传(使用element-ui框架)功能的完整代码如下:

路由 Api 接口:

// 导入模块
var express = require('express');
var router = express.Router();
var _ = require("lodash");
var path = require("path");
var multer = require('multer');

// 图片上传
// 文件上传的内置方法
var imgName = ""; // 这个是保存在路径里的名称
const storage = multer.diskStorage({
// 文件存储路径
destination(req, file, callback) {
// 上传的图片放到本地的文件夹里面
let imgUrl = "E:/qd/11. node.js/练习/test05_mongoDB/public/images"
// 回调函数
callback(null, imgUrl)
},
filename(req, file, callback) {
// 后缀名,到时候添加数据的时候,先把它设为空,然后进入图片上传页,然后做修改的操作
imgName = _.random(0, 9999999999999) + path.extname(file.originalname);
callback(null, imgName); // 把生成的名称放在这里

}  

});

// 也是内置函数
const addfild = multer({
storage
});

// 连接数据库
const {
MongoClient,
ObjectId
} = require("mongodb");

let url = "mongodb://127.0.0.1:27017";

let client = new MongoClient(url);

// 传参数:需要的数据,i(如果它为1,就查询,2就添加…),res:返回给客户端的数据
async function run(bookDate, i, res, req) {
try {
await client.connect();
let db = await client.db("book"); // 连接数据库的
let book = db.collection("bookInfo"); // 连接集合的
let result = ""; // SQL语句
// 执行哪个执行语句
if (i == 1) {
result = await book.find().toArray(); // 查询所有数据的
}
if (i == 2) {
// 获取图书编号
let id = parseInt(req.params.id);
// 查看id是什么类型的
console.log(typeof id);
// 执行语句
result = await book.deleteOne({
id: id
});
}
if (i == 3) {
// 获取通过post请求传递过来的参数
let inputText = req.body;
// 获取编号最大的图书,实现编号自动增长
let maxObj = await (book.find().sort({_id:-1}).limit(1)).toArray();
// 获取id和图片名称,把id 和 图片名称存进数据库里面
inputText.id = parseInt(maxObj[0].id) + 1;
inputText.picture = imgName;

        // // 执行语句  
        result = await book.insertOne(inputText);

        console.log(inputText);  
        console.log(maxObj);  
        console.log(inputText.id);  
    }  
    if (i == 4) {  
        console.log(parseInt(req.params.id));  
        result = await book.find({  
            id: parseInt(req.params.id)  
        }).toArray();  
        console.log(result);

    }  
    if (i == 5) {  
        let inputText = req.body;

        result = await book.updateOne({id:inputText.id}, {$set: {name: inputText.name,picture: imgName,author: inputText.author,price: inputText.price}});  
        console.log(result);  
    }

    // 返回客户端的信息  
    res.json({  
        status: "成功!",  
        data: result  
    });

} finally {  
    // 通常写关闭数据库的,但是,目前还不需要,因为只能查询一次,之后就关闭了!  
    // await client.close();  
}  

}

// 查询所有数据
router.get("/", (req, res, next) => {
// 调用run 方法,传参数
run("", 1, res, req);
});

// 删除
router.delete("/:id", (req, res, next) => {
run("", 2, res, req);
});

// 上传图片的
// 在这里传内置函数过去
router.post("/file", addfild.single('file'), (req, res, next) => {

})

// 添加
router.post("/", (req, res, next) => {
run("", 3, res, req);
})

// 渲染数据
router.get("/:id", (req, res, next) => {
run("", 4, res, req);
})

// 修改数据
router.put("/", (req, res, next) => {
run("", 5, res, req);
})

module.exports = router;

ejs 页面:


Document


图书管理系统


图书管理系统


编号 书名 封面 作者 价格 操作
{{ b.id }} {{ b.name }}
{{ b.author }} {{ b.price }}

    <!-- 模态框 -->  
    <div id="modal\_box">  
        <!--修改or添加  -->  
        <div id="mdinfo">  
            <table>  
                <tr>  
                    <td colspan="2" id="td">新增图书信息</td>  
                </tr>  
                <tr>  
                    <td>书名:</td>  
                    <td>  
                        <input type="text" id="name" class="text" v-model="bookObj.name" />  
                    </td>  
                </tr>  
                <tr>  
                    <td>作者:</td>  
                    <td>  
                        <input type="text" id="author" class="text" v-model="bookObj.author" />  
                    </td>  
                </tr>  
                <tr>  
                    <td>价格:</td>  
                    <td>  
                        <input type="text" id="price" class="text" v-model="bookObj.price" />  
                    </td>  
                </tr>  
                <tr>  
                    <td>封面名称:</td>  
                    <td>  
                        <input type="text" id="pictures" class="text" v-model="bookObj.picture" />  
                    </td>  
                </tr>  
                <tr>  
                    <td colspan="2">  
                        <button id="btn1" @click="save" class="btn">提交</button>  
                        <button id="btn2" class="btn">取消</button>  
                    </td>  
                </tr>  
            </table>  
        </div>  
    </div>  
</div>