Mongoose link database, add, delete, modify and query

Time:2021-2-11

According to personal coding habits, for reference only

If you look at it in the middle, you can go toOfficial website view

Introduction module

var mongoose = require("mongoose");

Connect to database

mongoose.connect("mongodb://localhost/mongoose_test");    

Link status

mongoose.connection.once("open",function () {
    console.log ("database link successful");
});
  • To see if the link is successful, make a callback

Creating schema objects

Example:

var Schema =  mongoose.Schema ; // will mongoose.Schema  Assign to variable
//Creating schema objects
var stuSchema = new Schema({
    name:String,
    age:Number,
    gender:{
        type:String,
        default:"female"
    },
    address:String
});

Official website:

Mongoose link database, add, delete, modify and query

Create model

Creating model through schema

The model represents the collection in the database. Only through the model can the database be operated. You canOfficial websitesee

Grammar:

mongoose.model(modelName, schema);
Parameter: modelname: the name of the collection to be mapped
Feature: mongoose: it will automatically change the collection name into a plural number

Example:

var StuModel = mongoose.model('student', stuSchema);

Add (insert document into database)

Grammar:

Model.create (DOC (s), [callback]); // used to create a document and add it to the database

Parameters:

  • dec(s)It can be a document object or an array of document objects
  • [callback]Optional callback function

Example:

StuModel.create({
    Name: "Baigujing",
    age:16,
    Address: "white bone cave"
},function (err) {
    if(!err){
        console.log ("insert successfully");
    }
});

query

Grammar:

Model.find (conditions, [projection], [options], [callback]); // an array is always returned by querying all qualified documents 
Model.findById (ID, [projection], [options], [callback]); // query the document according to its ID attribute
Model.findOne ([conditions], [projection], [options], [callback]); // querying the first qualified document always returns a specific document object

Parameters:

  • conditionsquery criteria
  • projectionProjection (field to get)

    • The first way{name:1,_id:0}
    • The second way"name -_id"
  • optionsQuery options(skip limit
  • callbackCallback function query result is returned through callback function. Callback function must be passed. If not, callback function will not be queried at all

Example:

StuModel.find ({Name: "Tang Seng"}, function (err, docs){
   if(!err){
       console.log(docs[0].name);
   }
});
StuModel.find({},{name:1, _id:0},function (err,docs) {
    if(!err){
        console.log(docs);
    }
});
StuModel.findById("5bac79be5fb5454418668515",function (err,doc) {
    if(!err){
        //The object returned by the result of find () query is the document object
        //A document object is an instance of a model
        console.log(doc instanceof StuModel)
    }
});

modify

Grammar:

Model.update (conditions, Doc, [options], [callback]); // used to modify one or more documents
Model.updateMany (conditions, Doc, [options], [callback]); // used to modify multiple documents
Model.updateOne (conditions, Doc, [options], [callback]); // used to modify a document
Model.replaceOne (conditions, Doc, [options], [callback]); // replace one

Parameters:

  • conditionsquery criteria
  • docModified object
  • optionsconfiguration parameter
  • callbackCallback function

delete

Grammar:

Model.remove (conditions, [callback]); // delete one or more
Model.deleteOne (conditions, [callback]); // delete one
Model.deleteMany (conditions, [callback]); // delete multiple

Example:

StuModel.remove ({Name: "Baigujing"}, function (ERR){
    if(!err){
        console.log ("delete successfully");
    }
})

Count the number of documents

Grammar:

Model.count(conditions,[callback])

Example:

StuModel.count({},function (err,count) {
    if(!err){
        console.log(count);
    }
});   

Document method

Document corresponds to the documents in the collection one by one. Document is an instance of model, and the result of model query is document

Create a document

var stu = new StuModel({
    Name: "Su Xiaoxiao",
    age:22,
    gender:"male",
    Address: "Shanghai"
});

Document method

Grammar:

 Model#save([options],[fn]);

Example:

stu.save(function (err) {
    if(!err){
        console.log (saved successfully)
    }
});

Modify, delete

Grammar:

Modify object: update (update, [options], [callback]);
Delete object: remove ([callback]);

Example:

StuModel.findOne({},function (err,doc) {
    if(!err){
        /**
         * update(update,[options],[callback])
             *- modify objects
         * remove([callback])
         *- delete objects
         */
       // console.log(doc);
       //  doc.update({$set:{age:28}},function (err) {
       //      if(!err){
       //           console.log ("modification successful");
       //      }
       //  })
        /**
         *Or
         */
        // doc.age = 18;
        // doc.save();
        
        
        
        // doc.remove(function (err) {
        //     if(!err){
        //          console.log (goodbye, senior brother);
        //     }
        // })


        /**
         * get()
         *- get the specified attribute value in the document
         * set(name,value)
         *- set the specified property value of the document
         *  id
         *- get the_ ID property value
         *  toJSON()
         *- convert to a JSON object
         *  toObject()
         *- convert the document object into a common JS object. Note that all the methods or properties of the document object cannot be used
         */

        //console.log(doc.get("name"))
        /**
         *Or
         */
        // console.log(doc.name)


        // doc.set ("name", "pig incompetence");
        /**
         *Or
         */
      //   doc.name  =Marshal Tianpeng;

        // console.log(doc._id);
        // var j = doc.toJSON();
        // console.log(typeof j);
        var o =doc.toObject()
        console.log(o)

    }
});

modularization

Create a new JS file to connect to the database
/**
 *Define a module to connect to mongodb database
 */
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/mongoose_test");
mongoose.connection.once("open",function () {
    console.log ("database link successful");
});
-------------------------------------------------------------------
Create a new JS file to create the student model
/**
 *Used to define the student model
 */
var mongoose = require("mongoose");

var Schema = mongoose.Schema;

var stuSchema = new Schema({
    name:String,
    age:Number,
    gender:{
        type:String,
        default:"female"
    },
    address:String

});
/**
 *Define the model
 */
var StuModel = mongoose.model('student', stuSchema);

/**
 *Exposed
 */
module.exports = StuModel;
----------------------------------------------------------------
Just introduce it where you need to call it
/**
 *Define a module to connect to mongodb database
 */
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/mongoose_test");
mongoose.connection.once("open",function () {
    console.log ("database link successful");
});