当前位置:网站首页>Node の MongoDB Driver
Node の MongoDB Driver
2022-07-05 10:38:00 【Hua Weiyun】
order
Prior to 《Node の MongoDB install 》 Among article , It mainly talks about how to install MongoDB And its visual interface Compass.
Now let's talk about node How to connect and use MongoDB, about node Connect , There are two ways , All download Libraries :
- mongodb: MongoDB There is a basic library
mongodb(Node.js MongoDB Driver) - Mongoose: Now the mainstream Library , Better in the amount of code , Just add, delete, modify and check the recommendation
mongodb
This is the basic library , But there are basic functions , If the demand is not too much, use this .
download
Installation command :yarn add mongodb
May refer to :https://www.mongodb.org.cn/drivers/5.html
Then create mongo The folder and index.js, It says in it mongodb How to use the library .
nodemon The main program running is main.js

Connect
First test mongodb Does the database exist , Whether it can be connected .
from mongodb Import... In the library MongoClient Client module , This module can be used to connect to the database
The test method is as follows :( there baseUrl It is based on the address of the previous database , You can also view the database to be connected in the visual interface 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(" Database created !"); db.close(); });}function :

But in fact, at this time, the database mongodbTest Not created , In the visual interface compass perhaps cmd None of them

then , I searched online for half a day , I found that this is only connected to 27017 Where? , No nonexistent database is created .( The code in this rookie tutorial should be wrong )

So let's create a database manually , You can create , A little bit more simple , Then you can create another set in the database .


Wait a minute , Next I'll go mongodb There was a wave of search on the official website , Finally, I successfully created the database with code , And the method on the rookie really doesn't work .
PS: There is a boiling point here , And dig you gave a relatively complete reply , Ha ha ha
The previous test connection method can be slightly modified , Use async and await To carry out , This makes the code look more comfortable .
mongodb official API:https://mongodb.github.io/node-mongodb-native/4.5/
It's used here MongoClient.db Method , This method will use or establish a database , however , If you don't create a collection for this database , Then this database will not be generated .
const baseUrl = 'mongodb://127.0.0.1:27017'// Create objects const client = new MongoClient(baseUrl);async function TestConnect() { try { // Connect to database await client.connect(); // Use the previously manually created mongodbTest database const db = await client.db('mongodbTest'); console.log(db.databaseName) // Create a new collection ( If the database is created by the code , Then you must create a set ) db.createCollection('collection01') } catch(e) { console.log(e) await client.close(); }}module.exports = { TestConnect }Get collection list
Now that you have successfully created the database , Then try to get all the collection information under the database collections, have access to collectionName Print out the names of these sets
// Connect to database await client.connect();// Use the previously manually created mongodbTest database const db = await client.db('mongodbTest');// Get all collections under the current database let collections = await db.collections();// Print set name collections.forEach(item=>{ console.log(item.collectionName)})Set list name :

After the above simple use of the database and set list , You can operate on a single set .
PS: For the database db Please refer to specific API file , The methods inside are also relatively comprehensive
Create a collection and insert data
Use here db Medium createCollection Method , Can be used to create new collections
createCollection Method parameter :
| Parameters | effect |
|---|---|
| name | Create the name of the collection |
| Optional | Command optional settings |
| callback | The callback method ,Callback<Collection<TSchema>> |
Test code :
// Create a new collection db.createCollection('collection03', { autoIndexId: true }, (err, res)=>{ if (err) console.log(' Collection creation failed '); console.log(res.collectionName) // collection03})After creating an empty collection , It's time to insert data into this set
stay mongodb in , Most of the collections are documents , Or the front end can be regarded as a key value pair JSON data
example : Define a document , And use insertOne Insert into the target set :
// Use set collection03let c3 = db.collection('collection03');// Define documents let doc = { name: ' Zhang San ', age: 18, hobby: ' Hit Li Si ',}// Insert the document into the collection const result = await c3.insertOne(doc);insertOne If the insertion is successful , Will return the current document in the collection id


There are the following methods for inserting documents into collections 3 Kind of :( The return values of these three methods are Promise, have access to async and await To solve the callback )
- insert: Insert a single document or an array of documents MongoDB. If the incoming document does not contain \u id Field , The driver will add a , Thus changing the document
- insertMany: Insert the document array MongoDB. If the incoming document does not contain \u id Field , The driver will add a , Thus changing the document
- insertOne: Insert a single document MongoDB. If the incoming document does not contain \u id Field , The driver will add a , Thus changing the document
Next try inserting a document array :
let doc = [ { name: ' Li Si ', age: 18, hobby: ' Beat Wang Wu ', }, { name: ' Wang Wu ', age: 18, hobby: ' Open three ', },]// Insert the document into the collection const result = await c3.insertMany(doc);

Read the data in the collection
The document content has been inserted into the database collection above , So how to read the data from the database ?
MongoDB The library provides find Method
| Method | effect |
|---|---|
| find | Create a cursor for the filter , This filter can be used for iterations MongoDB Result |
| findOne | Get the first document that matches the filter |
| findOneAndDelete | Find the document and delete it in an atomic operation , Need to write lock during operation |
| findOneAndReplace | Find the document and replace it in an atomic operation . Need to write lock during operation |
| findOneAndUpdate | Find the document and update it in an atomic operation . Need to write lock during operation |
Example : You need to use toArray Change my , Or you can use the callback method to view
// Read the data in the collection const res = await c3.find().toArray();console.log(res)
If when retrieving data , You need to filter out some useless data , So it can be find Write parameters to configure .
Use here projection Limit the fields returned , Set the property that does not need to be read to 0, Or set the content to be read as 1.
Be careful , It is better not to set 0 and 1, Just set the read perhaps Do not read . Otherwise, there may be an error :MongoServerError: Cannot do inclusion on field name in exclusion projection ( If you specify 0 and 1 value , There will be errors , Unless one of the fields is \u id Field )
The following example is to _id and age Do not read :
// Read the data in the collection const res = await c3.find({}, { projection: { _id: 0, age: 0 }}).toArray();console.log(res)result :

In the example above , Will find find The first parameter in the method is {}, Because this is the query object , Used to restrict search . You can use to filter .
query Example :
// Read the data in the collection const res = await c3.find({ name: / Zhang /}, { projection: { _id: 0, age: 0 }}).toArray();console.log(res)In this way, only Zhang San's information is returned :

Delete set information
Now try to delete the previously saved documents from the collection
There are also delete Delete method
| Method | effect |
|---|---|
| deleteOne | Delete a single document from the collection |
| deleteMany | Delete the document array from the collection |
// Read the data in the collection const res = await c3.deleteOne({ name: / Zhang /});console.log(res) // { acknowledged: true, deletedCount: 1 }
Update collection
The above has been written with additions and deletions , Now? curd There are updates left
| Method | effect |
|---|---|
| update | It is not recommended to use , It is recommended to use the following two |
| updateOne | Update a single document in the collection |
| updateMany | Update multiple documents in the collection |
Example :
// Read the data in the collection let newvalue = { $set: { hobby: ' Hit Li Si ' } }const res = await c3.updateOne({ name: / king /}, newvalue);console.log(res)here , Wang Wu's hobby in the database has changed from playing Zhang San to playing Li Si

That's all mongodb Basic use of Library , I didn't expect to write so much .
mongoose Save it for next time …
边栏推荐
- Go-3-第一个Go程序
- 非技术部门,如何参与 DevOps?
- 风控模型启用前的最后一道工序,80%的童鞋在这都踩坑
- How can non-technical departments participate in Devops?
- WorkManager學習一
- How did automated specification inspection software develop?
- Have you learned to make money in Dingding, enterprise micro and Feishu?
- Idea create a new sprintboot project
- Comparative learning in the period of "arms race"
- 【SWT组件】内容滚动组件 ScrolledComposite
猜你喜欢

Window下线程与线程同步总结

微信核酸检测预约小程序系统毕业设计毕设(8)毕业设计论文模板

Universal double button or single button pop-up

How does redis implement multiple zones?

Idea create a new sprintboot project

Workmanager Learning one

How do programmers live as they like?

SAP UI5 ObjectPageLayout 控件使用方法分享

【JS】提取字符串中的分数,汇总后算出平均分,并与每个分数比较,输出

Have you learned to make money in Dingding, enterprise micro and Feishu?
随机推荐
Go项目实战—参数绑定,类型转换
pytorch输出tensor张量时有省略号的解决方案(将tensor完整输出)
官网给的这个依赖是不是应该为flink-sql-connector-mysql-cdc啊,加了依赖调
DOM//
C语言实现QQ聊天室小项目 [完整源码]
字符串、、
How can PostgreSQL CDC set a separate incremental mode, debezium snapshot. mo
使用bat命令一键启动常用浏览器
AtCoder Beginner Contest 258「ABCDEFG」
Who is the "conscience" domestic brand?
非技术部门,如何参与 DevOps?
GO项目实战 — Gorm格式化时间字段
BOM//
WorkManager的学习二
中职组网络安全C模块全漏洞脚本讲解包含4个漏洞的脚本
AtCoder Beginner Contest 258「ABCDEFG」
[JS] array dimensionality reduction
flink cdc不能监听mysql日志,大家遇到过这个问题吧?
微信核酸检测预约小程序系统毕业设计毕设(6)开题答辩PPT
2022鹏城杯web

