1. Create a collection
There are two steps to create a set, - one is to set rules for the set, the other is to create a set and create mongoose An instance of the schema constructor creates a collection.
// mongoose.Schema() is a constructor to new an instance object //2. Set rules const courseSchema = new mongoose.Schema({ name: String, author: String , isPub1ished: Boolean }); //3. Create a collection using rules. The collection created here is also a constructor const Course = mongoose.model ('Course', courseSchema); //The first parameter is the collection name and the second is the collection rule. The collection actually generated in the database is named courses
1. Create a document
Creating a document is actually inserting data into a collection.
Method 1
There are two steps: ① create a collection instance.
② Call the save method under the instance object to save the data to the database.
//4. Create document insert data // Create collection instance object const course = new Course({ name: 'node.js', author: 'xc-dh', isPublished: true }); // Call the save method under the instance object to save the data to the database. course.save();
Method 2
All database related operations are asynchronous
Create document insert data Course.create({ name: 'JavaScript', author: 'Star sea', isPublished: false }, (err, result) => { console.log(err); console.log(result); }); // You can use promise's method Course.create({ name: 'JavaScript12', author: 'Star sea', isPublished: false }).then(result => console.log(result)).catch(err => console.log(err));
3. Import data from mongodb database
Find the installation directory of mongodb database and place the bin directory under the installation directory in the environment variable.
Under the project root directory, enter the following command to import
mongoimport -d database name - c collection name -- file data file to import
4. Query documents
find() method
Returns a set of documents
// Find documents by criteria (if the criteria is empty, find all documents) Course.find().then(result => console.log(result)) // Returns a collection of documents (in array form) [{ _id: 5c0917ed37ec9b03c07cf95f, name: 'node.js Basics', author: 'xc-dh' },{ _id: 5c09dea28acfb814980ff827, name: 'Javascript', author: 'xc-dh' }]
findOne() method
Return a document
// Find documents by criteria Course.findOne({name: 'node.js Basics'}).then(result => console.log(result)) // Only one document is returned, and the first one is returned by default { _id: 5c0917ed37ec9b03c07cf95f, name: 'node.js Basics', author: 'xc-dh' }
// Match greater than, less than // User.find({ // age: { // $gt: 20, / / greater than // $lt: 40 / / less than // } // }).then(result => { // console.log(result); // }); // Match the document containing the return code // User.find({ // hobbies: { // $in: ['knock code'] // } // }).then(result => { // console.log(result); // }); // Select the field to query, and add - before the field to indicate that this field will not be queried // User.find().select('name age -_id').then(result => { // console.log(result); // }); // Sort in ascending order according to the age field // User.find().sort('age').then(result => { // console.log(result) // }) // In descending order, add a negative sign // User.find().sort('-age').then(result => { // console.log(result) // }) // Skip how many pieces of data to skip limit the number of queries User.find().skip(2).limit(3).then(result => { console.log(result) })
5. Delete document
// Delete a single document. If the condition contains multiple documents, the first document matching the condition will be deleted by default, and the deleted document will be returned User.findOneAndDelete({ _id: '5c09f1e5aeb04b22f8460965' }).then(result => { console.log(result); }); // Delete multiple documents. If the condition is empty, all documents will be deleted by default and an object will be returned. n represents the number of documents deleted. OK indicates whether the deletion is successful User.deleteMany({}).then(result => console.log(result)) //{ n: 4, ok: 1, deletedCount: 4 }
6. Update documents
// Update single User.updateOne({query criteria}, {Value to modify}).then(result => console.log(result)) // Update multiple User.updateMany({query criteria}, {Value to change}).then(result => console.log(result))
// Update a single document. If multiple documents are satisfied, only the first one will be updated by default User.updateOne({ name: 'Li Si' }, { name: 'Li goudan' }).then(result => { console.log(result); }); // Update multiple documents {} is empty, that is, all documents are selected by default User.updateMany({}, { age: 45 }).then(result => { console.log(result); })
7. mongoose verification
When creating a collection rule, you can set the validation rule of the current field. If the validation fails, the insertion fails.
- required: true required field
- minlength: 3 minimum length of string
- maxlength: 20 maximum string length
- Min: the minimum value is 2
- max: 100. The maximum value is 100
- enum: ['html', 'css', "javascript, 'nodejs]
- trim: true removes spaces on both sides of the string
- validate: custom validator
- Default: default
- Get error information: error Errors ['field name'] message
// Validation rules can be followed by two parameters. The second parameter represents user-defined error prompt information const postSchema = new mongoose.Schema({ title: { type: String, // Required fields. If not, an error will be reported required: [true, 'Please pass in the article title'], minlength: 2, maxlength: [6, 'The title length cannot be greater than 6 characters'], trim: true //Remove spaces around the string }, age: { type: Number, min: 24, //Minimum value max: 80 //Maximum value }, publishDate: { type: Date, // Default value, the default value displayed when no information is inserted default: Date.now }, category: { type: String, // Enumeration that lists the values that the current field can have enum: ['HTML', 'css', 'javascript', 'node.js'] }, author: { type: String, // Custom validator validate: { validator: v => { // Returns a Boolean value // true validation succeeded // false validation failed // v value to verify return v && v.length > 4; }, // Custom error message message: 'The value you entered does not meet the validation rules' } } }); // Create a collection using rules const Post = mongoose.model('Post', postSchema); // The create method inserts data Post.create({ title: 'aaa', age: 68, category: 'javascript', author: 'db' }).then(result => console.log(result)) // Get error message .catch((error) => { // Get error information object const err = error.errors; // Circular error message object for (var k in err) { // console.log(err[k].message); // Print error message console.log(err[k]['message']); } })
8. Set Association
Generally, there is a relationship between the data of different sets. For example, the article information and user information are stored in different sets, but the article is published by a user. To query all the information of the article, including the publishing user, you need to use the set association.
- Associate collections with IDS
- Use the populate method to query association sets

// Association set const mongoose = require('mongoose'); // Connect to database mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true, useNewUrlParser: true }).then(() => { console.log('Database connection succeeded'); }).catch((error) => { console.log(error, 'Database connection failed'); }); // Create collection rule const userSchema = new mongoose.Schema({ name: { type: String } }); const postSchema = new mongoose.Schema({ title: { type: String }, // 1. Use the ID to associate the article collection with the author collection author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }); // Create collection const User = mongoose.model('User', userSchema); const Post = mongoose.model('Post', postSchema); // Insert document data // User.create({ // name: 'xc' // }).then(result => { // console.log(result); // }); // Post.create({ // title: 'html', // author: '5f9668bb20347221d49d0254' // }).then((result => { // console.log(result); // })); // 2. Joint query Post.find().populate('author').then(result => { console.log(result); })
//The returned results are as follows [{_id: 5f966a51c70ba932880c36d3, Title: 'HTML', author: {_id: 5f9668bb20347221d49d0254, name: 'XC', V: 0}, V: 0}]
9. Case: addition, deletion, modification and query of user information
- Build a website server to realize the communication between the client and the server
- Connect to the database, create a user collection, and insert documents into the collection
- When a user accesses / list, all user information is queried
- Splice the user information and table HTML, and respond the splicing results back to the client
- When the user accesses / add, the form page is presented and the function of adding user information is realized
- When the user accesses / modify, the modification page is presented and the function of modifying user information is realized
- When the user accesses / delete, the user deletion function is implemented