“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

In the previous article, I introduced how to use Mongoose to connect to the database. Now I will implement a simple CRUD.

schema

Schema is the model defined in Mongoose. Here we take students as an example to build a model

Student model

Students generally have, student number, name, age, class, hobbies and other attributes

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var stuObj = new Schema({
  stuNo: {
    / / type
    type: String.// Whether it is necessary
    required: true.// is it unique
    unique: true.// Remove the first space
    trim: true.// Minimum length
    minlength: 3.// Maximum length
    maxlength: 18,},name: {
    / / type
    type: String./ / must
    required: true.// Remove the first space
    trim: true.// Minimum length
    minlength: 2.// Maximum length
    maxlength: 10,},age: {
    type: Number./ / the default value
    default: 18,},loves: {
    // This hobby is a string array
    type: [String].default: []},address: {
    // The home address is an object type that must contain provinces and cities
    type: {
      province: {
        type: String.required: true,},city: {
        type: String.required: true,}},required: true}});// Map the model to the database
var StuSchema =  mongoose.model("Students", stuObj)
Copy the code

There are many ways to verify the model, check the specific document, here only show how to use

The new document

Now that the database is connected, the model is good, then the most model operation, all operations from the new start.

Method 1: Nodejs (callback function)

var obj = {
  stuNo: "20210101".name: " twinkle ".loves: ["code"."Beat the beans."].address: {
    province: "Jiangxi".city: "Ganzhou",}};// How to add students
var userModel = new StuSchema(obj);
userModel.save(function (err) {
  if (err) {
    console.log(err, '----- save failed ')}console.log('Saved successfully! ')})Copy the code

Code run result

The actual results of the database

Method two, using es6 notation

Since the model’s save method is a promise, it is certainly possible to handle it using promises at this point.

var obj = {
  stuNo: "20210102".name: " marry ".loves: ["Learning"."Or study?"].address: {
    province: "Jiangxi".city: "Ganzhou",}};// How to add students

async function  addStu(obj) {
  var userModel = new StuSchema(obj);
  var result = await userModel.save();
  console.log(result,'-- Save the result ')
}
addStu(obj)
Copy the code

Code run result

The actual results of the database

Pay attention to

Some people say, how always successful, we should need some failures to see the role of Mongoose, then we will see how to deal with this failure

1. Duplicate names

When the name is repeated, it triggers mongoose’s verification, and you report an error

2. Obj objects and models do not match more

When there are redundant fields, Mongoose will automatically remove them for you and save the data in an appropriate format according to schema rules.

3. Fewer obj fields

Here there is no doubt that the field is missing the affirmative trigger rule validation, error. I’m not going to do that

Because the above two methods, are only js update, in the future code writing, is definitely recommended to use ES6 above writing, so the following case will only use ES6 writing, node callback function writing method please experience.

Query the document

Add good data, then query data.

Querying documents with Mongoose is fairly easy and supports MongoDB’s advanced (Rich) query syntax. Documents can be queried using model’s find, findById, findOne, and WHERE static methods. Query more, here is only the most basic demonstration, details of the query behind the article.


async function findStu(name){
 var res =  await StuSchema.find({name:name});
 console.log(res);
}
findStu('twinkle');
Copy the code

The query result is as follows

If there is no result, what does the query return?

Modify the document

/** * Modify the document *@param {*} Condition conditions *@param {*} Contents modified by updCon */
async function updStu(condition, updCon){
  var res =  await StuSchema.update(condition,updCon);
  console.log(res);
 }
 updStu({name: 'mack'}, {name:'jack'})
Copy the code

The results of

But this method is out of date, and the console will issue a warning ⚠ :

Modified as follows:

/** * Modify the document *@param {*} Condition conditions *@param {*} Contents modified by updCon */
async function updStu(condition, updCon){
  var res =  await StuSchema.updateOne(condition,updCon);
  console.log(res);
 }

 updStu({name: 'jack'}, {name:'jack1'.abc:1232})
Copy the code

Careful students found that we added some invalid attributes in the modification. The results are still modifiable, but what is the actual content of the database?

delete

It doesn’t matter whether the writing is good or not, the people who can see here must be very cattle, I give you a thumbs up 👍👍👍

Delete is actually very simple as follows:

/** * delete document *@param {*} * / condition conditions
async function delStu(condition){
  var res =  await StuSchema.deleteOne(condition);
  console.log(res);
 }
 delStu({name:'jack1'})
Copy the code

Database real results

Some people would say the conditions don’t exist. Delete what?