文章目录

  • 一、安装MongoDB访问驱动
  • 二、连接数据库
  • 三、添加数据
  • 四、添加多条数据
  • 五、修改数据
  • 六、查询数据
    • 1、查询单条记录
    • 2、查询多条记录
  • 七、删除数据
  • 八、完整示例代码
    • 1、路由 Api 接口:
    • 2、运行结果:

MongoDB 对许多平台都提供驱动可以访问数据库,如C#、Java、Node.js等。下面一步一步带着大家在Nodejs中连接MongoDB

一、安装MongoDB访问驱动

命令如下:

全局安装驱动:npm install mongodb -g在当前项目中引入:npm install mongodb --save

二、连接数据库

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

三、添加数据

const { MongoClient } = require("mongodb");  //依赖MongoClientlet 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);

四、添加多条数据

const { MongoClient } = require("mongodb");  //依赖MongoClientlet 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);

五、修改数据

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、查询单条记录

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、查询多条记录

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大于等于202201let 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);

七、删除数据

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

八、完整示例代码

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

1、路由 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 页面:

<!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要重置为0this.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、运行结果:

Node.js详解(四):连接MongoDB相关推荐

  1. node.js详解Http服务器

    概念:Node.js提供了http模块.其中封装了一个高效的HTTP服务器和一个建议的HTTP客户端.    http.server是一个基于事件的HTTP服务器.内部有C++实现.接口由JavaSc ...

  2. node.js 详解

    目录 一. 初始node.js 1.为什么 JavaScript 可以在浏览器中被执行? 2. node.js 简介 3. node.js 查看是否安装 4. 运行文件 (1).在终端中输入 :nod ...

  3. Node.js详解(二):Node.js与JS的关系

    一.简介 Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,是一个让 JavaScript 运行在服务端的开发平台,它让 JavaScript 成为与PHP.Py ...

  4. 详解 TCP 连接的“三次握手”与“四次挥手”

    详解 TCP 连接的"三次握手"与"四次挥手" 前言 TCP的三次握手(Three-Way Handshake) 1."三次握手"的详解 2 ...

  5. linux 进程间通信 dbus-glib【实例】详解四(上) C库 dbus-glib 使用(附代码)(编写接口描述文件.xml,dbus-binding-tool工具生成绑定文件)(列集散集函数)

    linux 进程间通信 dbus-glib[实例]详解一(附代码)(d-feet工具使用) linux 进程间通信 dbus-glib[实例]详解二(上) 消息和消息总线(附代码) linux 进程间 ...

  6. 数据结构--图(Graph)详解(四)

    数据结构–图(Graph)详解(四) 文章目录 数据结构--图(Graph)详解(四) 一.图中几个NB的算法 1.普里姆算法(Prim算法)求最小生成树 2.克鲁斯卡尔算法(Kruskal算法)求最 ...

  7. Cocos2d之Node类详解之节点树(二)

    一.声明 本文属于笔者原创,允许读者转载和分享,只要注明文章来源即可. 笔者使用cocos2d框架的cocos2d-x-3.3rc0版本的源代码做分析.这篇文章承接上篇<Cocos2d之Node ...

  8. mybatis 鉴别其_MyBatis之Mapper XML 文件详解(四)-JDBC 类型和嵌套查询

    MyBatis之Mapper XML 文件详解(四)-JDBC 类型和嵌套查询 白玉 IT哈哈 支持的 JDBC 类型 为了未来的参考,MyBatis 通过包含的 jdbcType 枚举型,支持下面的 ...

  9. Grunt学习笔记002---Gruntfile.js详解

    Gruntfile.js详解 使用yeomen新建一个项目,里面会自动帮你创建一个完整项目的全部目录,这里针对新建出来的Gruntfile.js做一下简单说明,用作以后参考使用,由于还是菜鸟,很多东西 ...

最新文章

  1. 【PC工具】注意安全,建议使用:安全软件,谷歌输入法下载
  2. Android Telephony分析(三) ---- RILJ详解
  3. 前端学习(1532):项目1---项目功能展示
  4. ajax代码原理,关于Ajax的原理以及代码封装详解
  5. Parencodings 模拟
  6. Scrapy入门程序点评
  7. python编程输入法_用Python写一个拼音输入法
  8. 论文阅读_TASE: Reducing Latency of Symbolic Execution with Transactional Memory
  9. oracle中imp命令详解,Oracle中imp命令详解
  10. python求均值方差不用numpy_【Python】不用numpy用纯python求极差、平均数、中位数、众数与方差,python的打印到控制台...
  11. 是西电梦了我,还是我梦了西电
  12. Java 基础 - List 遍历时为什么不能通过 for 循环进行删除,而使用 Iterator 可以 ?
  13. NBA各队所在分区,州,城市,主体育馆资料整理
  14. 正向/逆向最大匹配法分词实现
  15. 音视频的同步原理——老文章,比较清晰
  16. php验签,在php中验证签名
  17. 统计输入字符串中大写字母、小写字母、阿拉伯数字个数和特殊符号的个数
  18. win10本地搜索应用没反应怎么解决?
  19. 狂神说smbms超市管理系统项目源码
  20. Android源码看设计模式(十二)--------关于观察者模式的Rxjava的相关分析

热门文章

  1. 搭建ELK7.3上的企业级分布式监控报警系统ElastAlert(邮箱)
  2. mkdir创建文件夹/目录 常用参数
  3. 预格式化文本pre标签
  4. 姚洋教授的学术讲座“如何做好经济学研究”
  5. 推荐一本有关嵌入式系统事件驱动编程的图书
  6. 【开启全民开发时代】无代码RPA 赋予业务人员IT能力,简单易学的工具化软件
  7. Scala篇—implicit隐式入门
  8. Unity Shader学习记录(15) —— Unity的光源类型
  9. 读书感受 之 《月亮与六便士》
  10. 小白如何学习黑客技术?