Node.js Detailed Explanation (4): Connecting to MongoDB


MongoDB provides drivers for many platforms to access databases, such as C#, Java, Node.js, etc. The following step by step will take you to connect MongoDB in Nodejs

insert image description here

1. Install the MongoDB access driver

The command is as follows:

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

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

Two, connect to the database

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);

3. Add data

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);

4. Add multiple pieces of data

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);

5. Modify data

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);

6. Query data

1. Query a single record

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);

2. Query multiple records

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);

7. Delete data

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);

8. Complete sample code

The complete code to connect to the MongoDB database and realize curd and image upload (using the element-ui framework) is as follows:

1. Routing Api interface:

// 导入模块
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 page:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="stylesheets/book.css">
    <link rel="stylesheet" href="stylesheets/index.css">
</head>

<body>
    <div id="app">
        <h3>图书管理系统</h3>
        <div id="addbtn">
            <!-- <div id="sort">
                <button id="sortId" @click="sortId">按id倒序</button>
            </div>
            <div id="search">
                <input type="text" name="" id="searchText">
                <button id="searchbtn" @click="search">搜索</button>
            </div> -->
            <button id="appBook">新增图书 + </button>
        </div>
        <table>
            <tr>
                <th>编号</th>
                <th>书名</th>
                <th>封面</th>
                <th>作者</th>
                <th>价格</th>
                <th>操作</th>
            </tr>
            <tr v-for="(b, i) in book" :key="b.id">
                <td>{
    
    {
    
     b.id }}</td>
                <td>{
    
    {
    
     b.name }}</td>
                <td>
                    <div id="picture" :style="{backgroundImage: 'url(/images/' + b.picture + ')'}"></div>
                </td>
                <td>{
    
    {
    
     b.author }}</td>
                <td>{
    
    {
    
     b.price }}</td>
                <td>
                    <button id="update" @click="edit(b.id)">编辑</button>
                    <button id="delete" @click="del(b.id)">删除</button>
                </td>
            </tr>
        </table>

        <!-- 模态框 -->
        <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 style="display: flex;">
                            <el-upload ref="mYupload" action="string" :http-request="handleChange"
                                list-type="picture-card" :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove" :on-change="handleChange">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                            <!-- <div class="Browse" :style="{backgroundImage: 'url(/images/' +  + ')'}"></div> -->
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <button id="btn1" class="btn" @click="save">提交</button>
                            <button id="btn2" class="btn" @click="cancel">取消</button>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</body>
<script src="javascripts/jquery-1.12.4.js"></script>
<script src="javascripts/axios.js"></script>
<script src="javascripts/vue.js"></script>
<script src="javascripts/index.js"></script>
<script>
    var path = "http://127.0.0.1:8082/bookApi/";
    var app = new Vue({
    
    
        el: "#app",
        data: {
    
    
            book: [],
            bookObj: {
    
     "id": 0, "name": "", "picture": "", "author": "", "price": "" },
            // 文件上传
            dialogImageUrl: '',
            dialogVisible: false,
            rawName: ""
        },
        created() {
    
    
            // 查询所有的数据
            this.selectData();
            // 把图片的名称赋值
            this.bookObj.picture = this.rawName;
        },
        methods: {
    
    
            // 查询
            selectData() {
    
    
                axios
                    .get(path)
                    .then((res) => {
    
    
                        this.book = res.data.data;
                    })
            },
            // 删除
            del(id) {
    
    
                if (confirm("您确定要删除这数据吗?")) {
    
    
                    axios
                        .delete(path + id)
                        .then((res) => {
    
    
                            console.log(id);
                            console.log(res);
                            alert("删除成功!");
                            // 调用查询全部的数据
                            this.selectData();
                        })
                }
            },
            // 文件上传的样式
            // 删除
            handleRemove(file, fileList) {
    
     },
            // 放大
            handlePictureCardPreview(file) {
    
    
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            // 添加封面图
            handleChange(file) {
    
    
                // 如果缩略图这个元素在的话,就删除这个这个,然后重新上传一个(其实就是为了方便修改图片)
                if ($('.el-upload-list__item').length > 0) {
    
    
                    // 删除缩略图图片
                    $(".el-upload-list__item").remove();
                }
                let formDate = new FormData();
                formDate.append('file', file.raw);
                // console.log(file.raw.name);
                formDate.append("file", file);
                axios
                    .post(path + "file", formDate)
                    .then((data) => {
    
    
                    });
                this.rawName = file.raw.name;
            },
            // 添加图书与修改图书
            save() {
    
    
                if (this.bookObj.id) {
    
    
                    // 修改
                    axios
                        .put(path, this.bookObj)
                        .then((data) => {
    
    
                            if (data.data.status === "成功!") {
    
    
                                // console.log(data.data.data);
                                alert("修改成功!");
                                this.bookObj = {
    
     id: 0, name: "", picture: "", author: "", price: "" };
                                $("#modal_box").css("display", "none");
                                // 删除缩略图图片
                                $(".el-upload-list__item").remove();
                                //  重新查询一次数据
                                this.selectData();
                            }
                        })

                } else {
    
    
                    // 添加
                    axios
                        .post(path, this.bookObj)
                        .then((data) => {
    
    
                            if (data.data.status === "成功!") {
    
    
                                // console.log(data.data.data);
                                alert("添加成功!");
                                this.book.id = 0; // 因为是添加,所以id要重置为0
                                this.bookObj = {
    
     id: 0, name: "", picture: "", author: "", price: "" };
                                $("#modal_box").css("display", "none");
                                // 删除缩略图图片
                                $(".el-upload-list__item").remove();
                                //  重新查询一次数据
                                this.selectData();
                            }
                        })
                }
            },
            // 编辑图书
            edit(id) {
    
    
                $("#td").html("修改图书信息");
                $("#modal_box").slideToggle();
                axios
                    .get(path + id)
                    .then((data) => {
    
    
                        this.bookObj = data.data.data[0];
                        // 寻找ul节点,然后创建li节点,并给li节点添加一个类,最后把li添加到ul里面
                        var ul = document.querySelector('ul');
                        var li = document.createElement("li");
                        li.className = "el-upload-list__item";

                        // 再创建一个img节点
                        var img = document.createElement("img");
                        //设置 img 图片地址、宽、高
                        img.src = "images/" + this.bookObj.picture;
                        img.width = 148;
                        img.height = 148;

                        ul.appendChild(li);
                        li.appendChild(img);

                        // console.log(this.bookObj);
                    })
            },
            // 模态框取消按钮
            cancel() {
    
    
                $("#modal_box").css("display", "none");
                $(".text").val("");
                // 删除缩略图图片
                $(".el-upload-list__item").remove();
            }
        }
    });

    // 模态框显示
    $("#appBook").click(function () {
    
    
        $("#modal_box").slideToggle();
        $("#td").html("新增图书信息");
    });

</script>

</html>

2. Running result:

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44816664/article/details/131717777