Mongod
- You can configure
mongodb
inndsk.config.js
module.exports = (isPro)=>{
return {
server:{
plugins:{
mongodb:{
name:"mongo", //Plugin Name
client:[
{
name:'client', //request.mongo.client or server.mongo.client
uri:'mongodb+srv://<db_username>:<db_password>@cluster0.rw45myx.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0',
config:{} //mongodb config
},
// {
// name:'client1', //request.mongo.client1 or server.mongo.client1
// uri:'mongodb+srv://********',
// config:{} //mongodb config
//}
]
}
}
}
}
}
server.plugins.mongodb.name
- A string, if you set
mongo
, userequest.mongo.client
orserver.mongo.client
to call, if you settest
, userequest.test.client
orserver.test.client
server.plugins.mongodb.client
-
An array, allowing to add multiple
mongodb
links -
Note: Your mongodb version must be >= v5.0
-
After successful configuration, you can use
request.mongo.client
in the route orserver.mongo.client
in the plugin for database operations
export default async (request)=>{
const mongo = request.mongo.client;
return await mongo.db('ndsk').collection('test').findOne()
}
exports.plugin = {
name: 'mongoTest',
register: (server) =>{
server.events.on('start', async () => {
const mongo = server.mongo.client;
const data = await mongo.db('ndsk').collection('test').findOne();
console.log(data)
});
}
}
Field validation
- Although
mongodb
has its own field validation function, it may not be easy to use for us. The framework has its own validation function. Let’s see how to implement it.
my-nodestack-app
├── src
│ ├── routes
│ │ │── mongodb
│ │ │ │── action.js
│ ├── mongodb
│ │ │── client
│ │ │ │── ndsk
│ │ │ │ │── test.js
├── ndsk.config.js
└── package.json
const Joi = require('joi');
//insert
export const insert = Joi.array().items({
username: Joi.string().default('rocky'),
age:Joi.number().min(0).error(new Error('age must be a number')).required(),
}).required().single();
//update
export const update = Joi.object().keys({
age:Joi.number().min(0).required()
}).required();
const Joi = require('joi');
export const options = {
validate:{
query:Joi.object({
action:Joi.string().valid('insertOne','updateOne').error(new Error('The value of the action parameter must be updateOne or insertOne')).required(),
age:Joi.any().required()
}),
}
}
export default async (request)=>{
const collection = request.mongo.client.db('ndsk').collection('test');
const {action,age} = request.query;
if(action === 'insertOne'){
await collection.insertOne({age});
}else{
await collection.updateOne({username:'rocky'},{$set:{age}});
}
return await collection.findOne({username:'rocky'});
}
-
We created the
src/mongodb/client/ndsk/test.js
file for verification, whereclient
corresponds to the data client name you configured inndsk.config.js
,ndsk
represents the database name, andtest
represents the collection name to be verified -
The above verification means that when
client
connects to thendsk
database to operate thetest
collection, theage
field must be a number and must be greater than 0 when inserted or modified. -
Visit http://127.0.0.1:3000/mongo/example?action=insertOne&age=30
-
Visit http://127.0.0.1:3000/mongo/example?action=insertOne&age=test
-
Visit http://127.0.0.1:3000/mongo/example?action=updateOne&age=20
-
Visit http://127.0.0.1:3000/mongo/example?action=updateOne&age=test
-
mongodb
uses Joi for field validation, you can view the relevant documentation aboutJoi
here
Note:
insert
should useJoi.array().items({...}).required().single()
for validation, because you may insert data in batchesupdate
should useJoi.object().keys({}).required()
for validation
Database management
- Use
request.mongo.client.admin
orserver.mongo.client.admin
to manage the database. Note:client
is the name you use to configure the database settings
const admin = request.mongo.client.admin; // server.mongo.client.admin should be used in plugins
admin
supports the following operation methods
createDatabase(db,collection)
- Create a database, requiring two mandatory parameters,
db
: database name,collection
: collection name, for example:
export default async (request,h)=>{
const admin = request.mongo.client.admin
await admin.createDatabase('ndsk_test','test'); //Create the ndsk database and add the test collection
return await admin.listDatabases();
}
listDatabases
- List available databases
buildInfo
- Retrieve server information for the current instance of the database client
serverInfo
- Retrieve server information for the current instance of the database client
serverStatus
- Server status
addUser
- Add a user to the database
removeUser
- Remove a user from the database
replSetGetStatus
- Get the ReplicaSet status
ping
- Ping the MongoDB server and retrieve the results
command
- Execute command #### startSession
- Transaction #### [watch
](https://mongodb.github.io/node-mon godb-native/3.6/api/MongoClient.html#watch) - monitoring
Operate the database
- Use
request.mongo.client.db(xxx)
orserver.mongo.client.db(xxx)
to get data, Note:client
is the name you set in the database configuration,xxx
represents the database name
const db = request.mongo.client.db('ndsk');
db
supports the following operation methods
createCollection
- Create a collection
renameCollection
- Rename a collection
dropCollection
- Delete a collection
dropDatabase
- Delete a database
listCollections
- List all collections
stats
- Get statistics for all databases
Operate collections
- Use
request.mongo.client.db('ndsk').collection(xxx)
to get collections
const collection = request.mongo.client.db('ndsk').collection('test');
collection
supports the following operation methods
find
- Batch query
aggregate
- Aggregate operation
insertOne
- Single insert
insertMany
- Batch insert
findOne
- 查找单个
updateOne
- 更新单个
updateMany
- 批量更新
replaceOne
- 替换文档
findOneAndUpdate
- Find and update a single document. Note When
upsert:true
is used, a unique index will be automatically added based on the query conditions to prevent multiple insertions during concurrency
findOneAndReplace
- Find and replace a single document. Note Same as above
deleteOne
- Delete a single document
deleteMany
- Batch delete documents
findOneAndDelete
- Find and delete the current document
count
- Get the number of documents matching the filter
countDocuments
- Same as above
estimatedDocumentCount
- Same as above
distinct
- Returns a list of distinct values for a given key in a collection
createIndex
- Create an index
createIndexes
- Create indexes in batches
indexInformation
- Retrieve index information for this collection.
dropIndex
- Delete index
dropIndexes
- Batch delete index
watch
- Monitor current collection operations
pagination
- A method customized specifically for paging queries, and automatically optimizes
aggregate
performance, which can make querying data at the tens of millions or even higher levels stress-free, use as follows
export default async (request)=>{
const collection = request.mongo.client.db('ndsk').collection('test');
return await collection.pagination({
query:{}, //Query condition, an object None
sort:{id:-1}, //sort, an object, default None
page:1, //Current page, default 1
limit:10, //Number of items displayed per page, default: None
count:{ limit:100000 }, //Maximum number of queries, default { limit:100000 }
// project:{}, //Field filter, default: None
// lookup:[], //Aggregate association, an array, default None
// group:{} //Aggregation group, an object Default None
},{maxTimeMS:500});
}