The document address: www.npmjs.com/package/mon…
Initialize the
The installation
npm install mongoose
Copy the code
The introduction of
const mongoose = require('mongoose');
Copy the code
Connecting to a Database
const mongoose = require('mongoose');
const config = require('./index');
mongoose.connect(
config.URL, // Database address
);
Copy the code
Success warning and failure warning
Connect () returns a connection whose status is pending, and we add success and failure alerts.
const db = mongoose.connection;
db.on('error'.() = >{
log4js.error('*** database connection failed ***')}); db.on('open'.() = >{
log4js.info('database connection successful ***')})Copy the code
Schema
Define a Schema
Mongoose started with Schema. Each schema maps to a MongoDB collection (database table) and defines the composition of the documents in the collection.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let blogSchema = new Schema({
title: String.author: String.body: String.date: { type: Date.default: Date.now },
});
Copy the code
Create a Model
We will convert the schema to a Model using the mongoose. Model (modelName, schema) function:
let Blog = mongoose.model('Blog', blogSchema); - parameters1: is the singular name of a collection, that is, when you do not have any collections in your database, when you connect to MongoDB using Mongoose and are ready to insert data, Mongoose will automatically create a name called`Blog`The collection. - parameters2: call`new Schema`Created by the`Schema`
Copy the code
Example is given to illustrate
Let’s use an example of creating a user to actually use it
The database has been connected successfully. Start by creating the user Schema
User Schema & Model
Create the file models/userSchema.js
/ / into the mongoose
const mongoose = require('mongoose')
// Define user Schema
const userSchema = mongoose.Schema({
'userId': Number./ / user ID
'userName': String./ / user name
'userPassword': String./ / password
'userEmail': String./ / email
'mobile': String./ / cell phone number
'createTime': { // Create time
type: Date.default: Date.now()
},
'updateTime': { // Update time
type: Date.default: Date.now()
},
});
// Create the user Model and export it
module.exports = mongoose.model('users', userSchema, "users");
Copy the code
Create a user
1. Check whether the required fields have been uploaded
2. Take the unique field to the database query, see there is duplication
let res = await User.findOne({$or: [{userName}, {userEmail}]}, '_id userName userEmail');
if(res) {
ctx.body = utils.fail('The system has detected duplicate users. The information is as follows:${res.userName}-${res.userEmail}`);
return;
}
Copy the code
3. The user’suserId
Field is self-growing, so we need to introduce another self-growing table, which is created with +1
- To create a
counters
table
- Model of user Id self-growth
const mongoose = require('mongoose');
const counterSchema = mongoose.Schema({
_id: String.sequence_value: Number
});
module.exports = mongoose.model('counters', counterSchema, 'counters');
Copy the code
- through
$inc: {sequence_value: 1}
implementationsequence_value
Since the growth of
const Counter = require('.. /models/counterSchema');
let doc = await Counter.findOneAndUpdate({_id: 'userId'}, {$inc: {sequence_value: 1}}, {new: true});
Copy the code
4. Create a user
Create a record with the save() method
const user = new User({
userId: doc.sequence_value,
userName,
userEmail,
userPassword: md5('123456'),
mobile
});
user.save();
Copy the code
The md5 dependency is used to generate the default password
Md5 document: www.npmjs.com/package/md5
Delete user
Get the userId of the user to be deleted, which is an array
The delete here is a soft delete, which is actually a batch modification of the user’s state using the updateMany() method
// An array of users to be deleted
let {userIds} = ctx.request.body;
// Soft delete Modify user status state: 2
let res = await User.updateMany({userId: {$in: userIds}}, {state: 2});
if (res.modifiedCount) {
// The deletion succeeded
}
Copy the code
Modifying User Information
Use findOneAndUpdate() to find and update user information
// User information to be updated
let {
userId, userName, userEmail, mobile
} = ctx.request.body;
// Query and update user information
let res = await User.findOneAndUpdate({userId}, {userEmail, mobile });
ctx.body = utils.success(res.userId, 'Data updated successfully');
Copy the code
Querying User Information
Use the find() method to query user information
Because the query was paginated, we wrapped a pager() utility function to return the number of queries and the query index skipIndex
function pager({pageNum=1, pageSize=10}) {
// If it is a string, convert it to a number
pageNum *= 1;
pageSize *= 1;
const skipIndex = (pageNum - 1) * pageSize;
return {
page: {
pageNum,
pageSize
},
skipIndex
}
}
Copy the code
Gets query criteria and pages and indexes
const {userId, userName, state} = ctx.request.query;
const {page, skipIndex} = utils.pager(ctx.request.query);
Copy the code
Collating query conditions
let params = {};
if (userId) params.userId = userId;
if (userName) params.userName = userName;
if(state && state ! ='0') params.state = state;
Copy the code
Querying User Information
// Query the list of all users based on the criteria
let query = User.find(params, {
userPassword: 0
});
let list = await query.skip(skipIndex).limit(page.pageSize);
let total = await User.countDocuments(params);
ctx.body = utils.success({
page: {
...page,
total
},
list
});
Copy the code