当前位置:网站首页>Node の MongoDB Driver
Node の MongoDB Driver
2022-07-05 10:12:00 【华为云】
序
在之前的《Node の MongoDB 安装》 一文当中,主要说的是如何安装MongoDB和其可视化界面Compass。
现在来说说node怎么连接使用MongoDB,对于node连接,可以使用两种方式,都是下载库:
- mongodb: MongoDB有一个基础库
mongodb(Node.js MongoDB Driver) - Mongoose: 现在主流使用的库,在代码量上更优,只需增删改查推荐
mongodb
这是基础库,不过基本的功能都是有的,如果需求不是太多使用这个即可。
下载
安装命令:yarn add mongodb
可参考:https://www.mongodb.org.cn/drivers/5.html
然后创建mongo文件夹和index.js,里面写mongodb库的使用方法。
nodemon运行的主程序是main.js

连接
首先测试mongodb数据库是否存在,能否进行相连。
从mongodb库中导入MongoClient客户端模块,该模块可以用来连接数据库
测试方法如下:(这里的baseUrl是依据之前数据库的地址,也可以在可视化界面中查看要连接的数据库url)

const MongoClient = require('mongodb').MongoClient;const baseUrl = 'mongodb://127.0.0.1:27017/mongodbTest'function TestConnect() { MongoClient.connect(baseUrl, function(err, db) { if (err) throw err; console.log("数据库已创建!"); db.close(); });}运行:

但其实此时数据库mongodbTest没有创建出来,在可视化界面compass或者cmd中都没有

然后,我在网上找了半天,发现这只是连接到了27017那里,没有将不存在的数据库创建出来。(这里菜鸟教程上的代码应该是不对的)

所以这里自己先手动创建一个数据库吧,可以在可视化界面中创建,简单一点,然后可以在数据库中再创建一个集合。


慢着,接下来我去mongodb官网进行了一波搜索,终于成功用代码创建上了数据库了,并且菜鸟上的方法确实不行了。
PS: 这里发了一波沸点,还有掘友给了比较完整的回复,哈哈哈
在之前的测试连接方法中可以稍作修改,使用async和await来进行,这样让代码看上去更舒服一些。
mongodb官方API:https://mongodb.github.io/node-mongodb-native/4.5/
这里用到了MongoClient.db方法,此方法会使用或者建立一个数据库,但是,如果没有给这个数据库创建集合,那么此数据库也不会生成出来的。
const baseUrl = 'mongodb://127.0.0.1:27017'// 创建对象const client = new MongoClient(baseUrl);async function TestConnect() { try { // 连接到数据库 await client.connect(); // 使用之前手动创建的mongodbTest数据库 const db = await client.db('mongodbTest'); console.log(db.databaseName) // 创建一个新的集合 (如果是代码新建的数据库,那么必须创建一个集合) db.createCollection('collection01') } catch(e) { console.log(e) await client.close(); }}module.exports = { TestConnect }获取集合列表
既然成功创建了数据库,那么尝试获取该数据库下的所有集合信息collections,可以使用collectionName将这些集合的名称打印出来
// 连接到数据库await client.connect();// 使用之前手动创建的mongodbTest数据库const db = await client.db('mongodbTest');// 获取当前数据库下所有集合let collections = await db.collections();// 打印集合名称collections.forEach(item=>{ console.log(item.collectionName)})集合列表名称:

上面对数据库和集合列表简单使用完了之后,可以对单个集合进行操作。
PS: 对于数据库db的操作方法可以参考具体的API文档,里面的方法也比较全面
创建集合并插入数据
这里使用db中的createCollection方法,可以用来创建新的集合
createCollection方法参数:
| 参数 | 作用 |
|---|---|
| name | 创建集合的名称 |
| Optional | 命令可选设置 |
| callback | 回调方法,Callback<Collection<TSchema>> |
测试代码:
// 创建新集合db.createCollection('collection03', { autoIndexId: true }, (err, res)=>{ if (err) console.log('集合创建失败'); console.log(res.collectionName) // collection03})创建完一个空集合后,就该给此集合插入数据了
在mongodb中,集合中大部分都是文档,或者前端可以看成键值对的JSON数据
实例:定义一个文档,并使用insertOne插入到目标集合当中:
// 使用集合collection03let c3 = db.collection('collection03');// 定义文档let doc = { name: '张三', age: 18, hobby: '打李四',}// 将文档插入集合const result = await c3.insertOne(doc);insertOne插入如果成功,将会返回当前文档在集合中的id


关于插入文档到集合中的方法有以下3种:(这三种方法的返回值都是Promise,可以使用async和await来解决回调)
- insert: 将单个文档或文档数组插入MongoDB。如果传入的文档不包含\u id字段,驱动程序将向缺少该字段的每个文档中添加一个,从而改变文档
- insertMany: 将文档数组插入MongoDB。如果传入的文档不包含\u id字段,驱动程序将向缺少该字段的每个文档中添加一个,从而改变文档
- insertOne: 将单个文档插入MongoDB。如果传入的文档不包含\u id字段,驱动程序将向缺少该字段的每个文档中添加一个,从而改变文档
接下来试试插入文档数组:
let doc = [ { name: '李四', age: 18, hobby: '打王五', }, { name: '王五', age: 18, hobby: '打张三', },]// 将文档插入集合const result = await c3.insertMany(doc);

读取集合中的数据
在上面已经将文档内容插入到数据库的集合当中了,那么如何将数据从数据库中读取出来呢?
MongoDB库提供了find方法
| 方法 | 作用 |
|---|---|
| find | 为过滤器创建游标,该过滤器可用于迭代MongoDB的结果 |
| findOne | 获取与筛选器匹配的第一个文档 |
| findOneAndDelete | 查找文档并在一个原子操作中删除它,在操作期间需要写锁 |
| findOneAndReplace | 查找文档并在一个原子操作中替换它。在操作期间需要写锁 |
| findOneAndUpdate | 查找文档并在一个原子操作中更新它。在操作期间需要写锁 |
示例: 这里需要用toArray转换一下,或者也可以使用回调方法查看
// 读取集合中数据const res = await c3.find().toArray();console.log(res)
如果检索数据时,需要过滤掉一些无用的数据,那么可以在find中写入参数进行配置。
这里使用projection限制返回的字段,将不需要读取的属性设置为0,或者将需要读取的内容设置为1。
注意,这里最好不要同时设置出0和1,只需要设置读取或者不读取即可。否则可能会出现报错:MongoServerError: Cannot do inclusion on field name in exclusion projection (如果在同一对象中同时指定0和1值,则会出现错误,除非其中一个字段是\u id字段)
以下示例就是将_id和age不进行读取:
// 读取集合中数据const res = await c3.find({}, { projection: { _id: 0, age: 0 }}).toArray();console.log(res)结果:

在上面的示例中,会发现find方法中第一个参数是{},因为这是查询对象,用于限制搜索的。可以使用来筛选。
query示例:
// 读取集合中数据const res = await c3.find({ name: /张/}, { projection: { _id: 0, age: 0 }}).toArray();console.log(res)这样返回的结果只有张三的信息了:

删除集合信息
现在尝试去将之前存入的文档从集合中删除
同样也有delete删除方法
| 方法 | 作用 |
|---|---|
| deleteOne | 从集合中删除单个文档 |
| deleteMany | 从集合中删除文档数组 |
// 读取集合中数据const res = await c3.deleteOne({ name: /张/});console.log(res) // { acknowledged: true, deletedCount: 1 }
更新集合
上面已经写好了增删查,现在curd还剩下更新
| 方法 | 作用 |
|---|---|
| update | 不推荐使用,建议使用下面两种 |
| updateOne | 更新集合中的单个文档 |
| updateMany | 更新集合中的多个文档 |
示例:
// 读取集合中数据let newvalue = { $set: { hobby: '打李四' } }const res = await c3.updateOne({ name: /王/}, newvalue);console.log(res)此时,数据库中王五的爱好就从打张三变成了打李四

以上就是mongodb库的基本使用,没想到会写这么多。
mongoose留到下次了…
边栏推荐
- Interview: how does the list duplicate according to the attributes of the object?
- Qt实现json解析
- Events and bubbles in the applet of "wechat applet - Basics"
- "Everyday Mathematics" serial 58: February 27
- How does redis implement multiple zones?
- ByteDance Interviewer: how to calculate the memory size occupied by a picture
- Interview: is bitmap pixel memory allocated in heap memory or native
- Z-blog template installation and use tutorial
- CSDN always jumps to other positions when editing articles_ CSDN sends articles without moving the mouse
- Constrained layout flow
猜你喜欢

重磅:国产IDE发布,由阿里研发,完全开源!
![[论文阅读] KGAT: Knowledge Graph Attention Network for Recommendation](/img/fa/d2061bc7bd437f062d46a009cf32cf.png)
[论文阅读] KGAT: Knowledge Graph Attention Network for Recommendation

uniapp + uniCloud+unipay 实现微信小程序支付功能

Constraintlayout officially provides rounded imagefilterview

字节跳动面试官:一张图片占据的内存大小是如何计算

伪类元素--before和after

WorkManager的学习二

Design of stepping motor controller based on single chip microcomputer (forward rotation and reverse rotation indicator gear)

AD20 制作 Logo

How to plan the career of a programmer?
随机推荐
Timed disappearance pop-up
Blockbuster: the domestic IDE is released, developed by Alibaba, and is completely open source!
Uni app running to wechat development tool cannot Preview
报错:Module not found: Error: Can‘t resolve ‘XXX‘ in ‘XXXX‘
Lepton 无损压缩原理及性能分析
AtCoder Beginner Contest 258「ABCDEFG」
B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条...
请问大佬们 有遇到过flink cdc mongdb 执行flinksql 遇到这样的问题的么?
Activity enter exit animation
QT implements JSON parsing
Singleton mode encapsulates activity management class
mongoDB副本集
Learning note 4 -- Key Technologies of high-precision map (Part 2)
How to plan the career of a programmer?
How can non-technical departments participate in Devops?
SAP ui5 objectpagelayout control usage sharing
isEmpty 和 isBlank 的用法区别
Interview: is bitmap pixel memory allocated in heap memory or native
WorkManager的学习二
Tianlong Babu TLBB series - about items dropped from packages

