This is the fifth day of my participation in the August Wen Challenge.More challenges in August
1. Database overview and environment construction
1.1 What is a Database
Database is a warehouse for storing data, which can store data in an orderly manner. It is independent of language and can be operated through API
Common examples are: mysql,mongoDB, and Oracle
1.2 Database Related Concepts
Multiple databases can be contained in a database software, multiple data sets can be contained in each database warehouse, and multiple documents can be contained in each data set
1.3Mongoose Third-party package
- To operate the MongoDB database using Node.js, you need to rely on the third-party Node.js package Mongoose
- usenpm install mongooseThe command to download
- Run in a command line toolnet start mongoDBStart mongoDB; otherwise, mongoDB cannot connect
1.4 Connecting a Database
Connect to the database using the Connect method provided by Mongoose
Mongoose. Connect (' mongo: / / localhost/playground '), then (() = > {the console. The log (' database connection success ')}) .catch(err=>console.log(' database connection failed ',err))Copy the code
1.5 Creating a Database
There is no need to create a database in mongodb. If the database in use does not exist, mongodb will create it automatically
2. Add, delete, modify, and check MongoDB
2.1 Creating a Collection
The first step is to set rules for the collection and the second step is to create the collection. You can create the collection by creating an instance of the Mongoose. Schema constructor
// Set the set rule const courseSchema = new mongoose.Schema({name:String, author:String, isPublished:Boolean}); // create set and apply rule const Course = mongoose. Model ('Course',courseSchema); //coursesCopy the code
2.2 Creating a Document
Creating a document is essentially inserting data into the collection
There are two steps:
- Creating a collection Instance
- Call the save method under the instance object to save the data to the database
Const course = new course ({name:' node.js course ', author:'badspider', tags:[' Node ','backend'], isPublished:true }); // Save the data to the database.Copy the code
Second method (asynchronous)
Course. Create ({name:'javascript',author:'badspider',isPubliced:true},(err,doc)=>{// Error object console.log(err) // The current inserted document console.log(doc) })Copy the code
2.3 Importing data to the mongodb Database
Mongoimport -d database name -c collection name –file Specifies the data file to import
2.4 Querying Documents
Find (). Then (result => console.log(result)) // Return document set [{_id:ashdahdakja, name:'node.js', author:'badspider' },{ _id:aa2323dakja, name:'node.js', author:'badspider' } ]Copy the code
You can also use the find () method to find data with the _id:’ XXXX ‘
user.find({_id:'xxxxxxxx'}).then(result=>console.log(result))
The findOne method returns a document, which by default returns the first document in the current collection
User.findone ({name:'node.js'}). Then (result=>console.log(result)) {_id:ashdahdakja, name:'node.js', author:'badspider' }Copy the code
- Match greater than or less than
User.find({age: {$gt: 20, $lt: 50}}). Then (result => console.log(result))Copy the code
Select * from age 20 to 50
- Matching contains
User. The find ({hobbies: {$in: [' sleep sleep]}}), then (result = > console. The log (result)Copy the code
- Select the fields you want to query (if there are any fields you don’t want to query, add -as: -_id)
User.find().select('name email').then(reslut => console.log(result))
Copy the code
- Sort the data by age
User.find().sort('age').then(result => consloe.log(result)) consloe.log(result))Copy the code
- Skip Limit Specifies the number of queries to be skipped
User.find().skip(2).limit(2).then(result => console.log(result))
Copy the code
2.5 Deleting a Document
-
Removing a single
A document is found and deleted
Returns the deleted document
If the query criteria match multiple documents, the first matching document is deleted
Course.findOneAndDelete({}).then(result => console.log(result))`
Copy the code
- To delete multiple
User.deleteMany({}).then(result => console.log(result))
Copy the code
2.6 Updating Documents
- Update a single
User.updataone ({query condition},{change value}).then(result => console.log(result))Copy the code
- Update multiple
User.updatamany ({query condition},{change value}).then(result => console.log(result))Copy the code
2.7 mongoose validation
When creating a collection rule, you can set the validation rule for the current field. If the validation fails, the input fails to be inserted
- Required :true The required field
const posrSchema = new mongoose.Schema({ title:{ type: String, required:[true,' please pass in information '],// You can define error message minLength :2, // Maxlenght :5,// Maximum length trim: True, // remove Spaces on both ends of string min:2, // minimum value Max :12 // maximum value}, publishDate:{type:Date, // Default value default: Date.now}, category:{type:String, Enum :[' HTML ',' CSS ','javascript','node.js']}, author:{type:String, validate:{validator: V => {// returns a Boolean value //true validation succeeded //false validation failed //v validates the value to be validated return v && v.length >4}, // custom error message:" the value passed does not comply with the validation rule "}}}); const post = mongoose.model('Post',postSchema); post.creat({title:'aa',age:55,category:'html',author:"bd"}).then(result => console.log(result)).catch(error => console.log(error))Copy the code
- Get an error message
.catch(error => {// Get an error message object const err = error. Errors; For (var attr in err){console.lo(err[attr]['message'])}})Copy the code
2.8 Set Association
Generally, there is a relationship between data of different sets. For example, article information and user information are stored in different sets. However, an article is published by a certain user
- Use id to associate collections
- Use the Popilate method for associative collection queries
// Const User = mongoose. Model ('User',new mongoose.SChema({name:{type:String}})); // Const POst = Mongoose. Model (" POst ",new mongoose.Schema({title:{type:String}, / / use the ID will be associated author sets, and the author set: {type: mongoose. Schema. Types. The ObjectId, ref: "User"}})); Post.find().populate('author').then((err,result) => console.log(result));Copy the code
\