当前位置:网站首页>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 …
边栏推荐
- 微信核酸检测预约小程序系统毕业设计毕设(7)中期检查报告
- Qt实现json解析
- beego跨域问题解决方案-亲试成功
- Timed disappearance pop-up
- Web Components
- How can non-technical departments participate in Devops?
- Comparative learning in the period of "arms race"
- Apple 5g chip research and development failure? It's too early to get rid of Qualcomm
- How can PostgreSQL CDC set a separate incremental mode, debezium snapshot. mo
- BOM//
猜你喜欢
Idea create a new sprintboot project
双向RNN与堆叠的双向RNN
WorkManager學習一
How do programmers live as they like?
Ad20 make logo
csdn软件测试入门的测试基本流程
Comparative learning in the period of "arms race"
Pseudo class elements -- before and after
In the year of "mutual entanglement" of mobile phone manufacturers, the "machine sea tactics" failed, and the "slow pace" playing method rose
The most complete is an I2C summary
随机推荐
Workmanager learning 1
[paper reading] kgat: knowledge graph attention network for recommendation
How to plan the career of a programmer?
BOM//
Write double click event
脚手架开发基础
【观察】跨境电商“独立站”模式崛起,如何抓住下一个红利爆发时代?
Pseudo class elements -- before and after
A large number of virtual anchors in station B were collectively forced to refund: revenue evaporated, but they still owe station B; Jobs was posthumously awarded the U.S. presidential medal of freedo
双向RNN与堆叠的双向RNN
2022年流动式起重机司机考试题库及模拟考试
Workmanager Learning one
DDOS攻击原理,被ddos攻击的现象
5g NR system architecture
> Could not create task ‘:app:MyTest. main()‘. > SourceSet with name ‘main‘ not found. Problem repair
2022年化工自动化控制仪表考试试题及在线模拟考试
How can PostgreSQL CDC set a separate incremental mode, debezium snapshot. mo
函数///
5G NR系统架构
Livedata interview question bank and answers -- 7 consecutive questions in livedata interview~