Mongodb learning note 3 – mongooseapi operation data

Time:2021-12-29

In the last article, we talked about how to passMongooseTo dynamically add data to the database, let’s take a look at how to useMongooseTo add, delete, modify and query the database

Method of model object

  • remove(cinditions,callback)
  • deleteOne(conditons.callback)
  • deleteMant(conditions,callback)
  • find(conditions,projection,options,callback)
  • findById(id,projection,options,callback)
  • findOne(conditions,projection,options,callback)
  • count(conditions,callback)
  • create(doc,callback)
  • update(conditions,doc,options,callback)
  • wait

1. Pre code

//Introduce mongoose module
const mongoose = require("mongoose");

//Connect to database
mongoose.connect("mongodb://localhost:27017/test",{useNewUrlParser: true ,useUnifiedTopology: true});

//Test whether the connection is successful
mongoose.connection.once("open", function () {
    //Connection successfully executed
    console. Log ('connection succeeded ~ ';
});

//Create a schema object and assign it to a variable
const Schema = mongoose.Schema;

//Create a schema object
const stuSchema = new Schema({
    name: String,
    age: Number,
    gender: {
        type:String,
        Default: 'male'
    },
    address:String
});

//Create model through scheme
//Model represents the collection in the database. Only through model can the database be operated
// mongoose.model(modelName,schema);
//Modelname: is the name of the set to be mapped. Mongoose will automatically change the set name to a plural
//Schema: created schema object


const stuModel = mongoose.model('student', stuSchema);

2. Query documents

demonstration:

  • find(conditions,[projection],[options],[callback])-Query all qualified documents
stuModel.find({}, {name:1,_id:0}, function (err,docs) {
    if (!err) {
        console.log(docs)
    }
})

Operation results:
在这里插入图片描述

{skip: 3, limit: 1}: it means to skip three pieces of data and display one piece of data
stuModel.find({}, { name: 1, _id: 0 }, {skip:3,limit:1},function (err,docs) {
    if (!err) {
        console.log(docs)
    }
})

在这里插入图片描述


  • findById(id,[projection],[options],[callback])-According to the of the document_idAttribute query document
stuModel.findById("611a9aa01647216accf385fa", function (err, docs) {
    console.log(err)
    if (!err) {
        console.log(docs)
    }
})

在这里插入图片描述


  • findOne(conditions,[projection],[options],[callback])-Query the first document that meets the criteria
stuModel.findOne({}, { name: 1 },function (err,docs) {
    if (!err) {
        console.log(docs)
    }
});

在这里插入图片描述

Parameter resolution:

  • Conditions: query conditions
  • Projection: projection
    • In the two methods, the effect projected by the following two methods is the same
    • {name:1,_id:0}
    • "name -_id
  • Options: Query options(skip, limit)
  • Callback: callback function. Query results will be returned through the callback function

**Note: * * the object returned from the query result of find() is the document object
The document object is an instance of the model
The verification code is as follows:

stuModel.findById("611a9aa01647216accf385fa", function (err, docs) {
    if (!err) {
        console.log(docs instanceof stuModel)
    }
})

在这里插入图片描述


3. Modify document

  • update(conditions,doc,[options],callback)
  • updateMany(conditions,doc,[options],callback)
  • updateOne(conditions,doc,[options],callback)
  • replaceOne(conditions,doc,[options],callback)-Replace the existing document with the given document

parameter

  • conditions: query criteria
  • doc: modified objects
  • options: configuration parameters
  • callback: callback function
//Modification_ For data with ID 611a9aa01647216accf385fa, change the name to Zhang San
stuModel. Update ({_id: '611a9aa01647216accf385fa'}, {$set: {Name: 'Zhang San'}}, function (err, DOC){
    console.log(err, doc);
});

在这里插入图片描述
在这里插入图片描述


4. Delete document

  • remove(cinditions,callback)
  • deleteOne(conditons.callback)
  • deleteMant(conditions,callback)
//Delete the data with name: 'Zhang San' in the document
stuModel. Remove ({Name: 'Zhang San'}, function (err, DOC){
    if (!err) {
        console.log(doc);
        console. Log ('deletion succeeded ')
    }
})

在这里插入图片描述

supplement

  • Model.count(conditions , callback )
    • conditions : condition
    • callback: callback function
stuModel. Count ({Name: 'Xiaoming'}, function (err, count){
    console.log(count);
} )

在这里插入图片描述

Document object

  • adoptModelWhen querying the database, it returnsDocumentObject orDocumentObject combination
  • DocumentInherited fromModelRepresents the documents in a collection
  • DocumentObjects can also interact with the database

Method of document object

  • equals(doc)
  • id
  • get(path,[type])
  • set(path,value,[type])
  • update(update,[options,callback])
  • save([callback])
  • remove([callback])
  • isNew
  • isInit(path)
  • toJSON()
  • toObject()

The preceding code is the same as above:
demonstration

1. Insert data

  • save([callback])
const stuModel = mongoose.model('student', stuSchema);


//Create a document
var stu1 = new stuModel({
    Name: 'Lu Mingfei',
    age: 24,
    Gender: 'male',
    Address: 'Kassel College'
});

// console.log(stu1);

//Call the document API to save the data to the database
stu1.save(function (err) {
    if (!err) {
        console. Log ('saved successfully ');
    }
})

在这里插入图片描述
在这里插入图片描述


2. Update data

  • update(update,[options,callback])
//The method in mongoose can also use promise
stuModel.findOne({}).then(res => {
    res.update({ $set: { age: 22 } }).then(res => {
        console. Log ('modification succeeded ');
    })
})
//Update data method 2
stuModel.findOne({}).then(res => {
    res.age = 25;
    res.save();
})
  • set(path,value,[type]): set the corresponding attribute value according to the current document object
// set()
stuModel. Findone ({Name: 'Chu Zihang'}) then(res => {
    console.log(res.set("age",15));
})

在这里插入图片描述

3. Delete data

  • remove([callback])
//Remove ([callback]) - delete data
stuModel. Findone ({Name: 'Chu Zihang'}) then(res => {
    res.remove()
})

4. Obtain data

  • get(path,[type]): get the properties of the current document object
stuModel. Findone ({Name: 'Chu Zihang'}) then(res => {
    console.log(res.get('name'))
})

在这里插入图片描述


5. Convert data format

  • toJSON(): convert to aJSONobject
// toJSON()
stuModel. Findone ({Name: 'Chu Zihang'}) then(res => {
    console.log(res.toJSON());
})
  • toObject()Will:documentObject to an ordinary JS object
  • Convert to normaljsAfter the object, pay attention to allDocumentObject’s methods or properties cannot be used
// toObject()
stuModel. Findone ({Name: 'Chu Zihang'}) then(res => {
    console.log(res.toObject());
})