In professional courses, the teacher often told us that the operation of database is nothing more than adding, deleting, checking and modifying, namely CURD, which is exactly the fact. Next, we will look at mongoose’s operation of CURD of MongoDB, the no SQL database.

Common operating conditions and apis

Common query conditions

$gt > $gte > = $lt > $lte < = $ne > = $in > = $nin > = $nin > = $all > = $regex. Fuzzy query $size matching array size $maxDistance range query, distance (based on LBS) $mod calculation $NEAR neighborhood query, $elemMatch; $within; $box; $center; The circular range (based on LBS) $centerSphere range query, the spherical range (based on LBS) $slice query the elements in the field set (such as the NTH to the MTH element after the number)

Common query apis, see the documentation for details

Model.deleteone () removes the first document in the set of documents matching the condition, operation, and callback. Model.deleteone () removes the first document in the set of documents matching the condition, operation, and callback. Model.findbyid (); findOne({_id: = “findOne”); FindByIdAndDelete () most of the time it is used to query a document with the _id field and delete the equivalent of findOneAndDelete({_id: FindByIdAndRemove () queries a document with the _id field and removes the equivalent of findOneAndRemove({_id: FindByIdAndUpdate () queries a document with the _id field and updates the equivalent of findOneAndUpdate({_id: id},…). FindOne () queries a document with the following parameters: condition, select field, operation, callback model.findoneandDelete () queries a matching document and deletes the following parameters: Model.findoneandremove () queries a matching document and removes it with the following parameters: Condition, update field, action, callback model.replaceOne () overwrites an existing document equivalent to the update() arguments, respectively: Conditions, update fields, actions, callbacks Model.updatemany () updates multiple existing documents equivalent to the update() parameters: Model.updateone () updates an existing document with the following parameters: condition, update field, operation, callback Model.remove() removes all matching document parameters: Model.update() updates a document with the following parameters: condition, update field, action, callback

For the difference between findByIdAndDelete() and findByIdAndRemove(), remove the official documentation.

1. Connect to the database

Please refer to the Mongoose documentation for detailed documentation of the connection data.

Then callback mode

Assume that the database connection address for directing: / / localhost: 27017 / TestDB

Assume that the data operation Model is:

// peopleModel.js
let mongoose = require('mongoose');

let Schema = mongoose.Schema;

let PeopleSchema = new Schema({
  name: String.age: Number.sex: Number.class: String
});

module.exports = mongoose.model('People', PeopleSchema, 'peopleCollection');
Copy the code
const mongoose = require("mongoose");

var mongourl = 'mongodb://localhost:27017/TestDB';
mongoose.connect(mongourl).then(
  (a)= > { 
      console.log('Connection successful! ')
  },
  err => {
      console.log('go wrong! ', err); });Copy the code

On Listening mode

let mongoose = require('mongoose');

let mongoURL = 'mongodb://localhost:27017/TestDB';
mongoose.connect(mongoURL);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error'.console.error.bind(console.'MongoDB connection error:'));
db.once('open'.function() {
  // we're connected!
});
Copy the code

2. Query data

let express = require('express');
let router = express.Router();

let mongoose = require('mongoose');
let People = require('.. /models/peopleModel');

router.get('/'.function(req, res, next){
	
	// Use body-parse middleware to get the parameters
  letfilters = { ... req.query };console.log(filters, 'filter');

	// The field to query
  let query = {};

  if(filters.name){
    query.name = filters.name
  }
  if(filters.age){
  	// Query the age greater than age parameter
    query.bookInfo = {$gt: filters.age}
  }

  People.find(query, null, { 
	limit: filters.pageSize, 
	skip: (filters.pageSize * filters.pageNum), 
	sort:'-createBy.age'
  }, (err, data) => { // Find all
     if(err){
       res.status(500).json({ error: err });
     }else{
       res.json({ code: 1.data: data }); }})});module.exports = router;
Copy the code

When the front end sends corresponding data, data paging can be realized by filtering and extracting paging fields and using limit and SKIP operations. Mongoose-paginate plug-in can also be used to simplify paging operations. After the front end sends corresponding filtering fields, results will be searched according to corresponding fields. The age value is returned in reverse order.

2. Add data

Mongoose’s save() method is used to add data

let express = require('express');
let router = express.Router();

let mongoose = require('mongoose');
let People = require('.. /models/peopleModel');

router.post('/'.function(req, res, next){
  const name = req.body.name,
    age = req.body.age,
    sex = req.body.sex,
    class = req.body.class;

  const newPeople = new People({
    name,
    age,
    sex,
    class
  });

  // Add a save
  newPeople.save((err, data) = > {
    if(err){
      res.status(500).json({ error: err });
    }else{
      res.json({ code: 1.data: data }); }}); });module.exports = router;

Copy the code

3. Modify data

Data modification requires the _ID field, which is automatically generated every time a new record is added to the MongoDB database and is also the unique identifier. Meanwhile, the findByIdAndUpdate() method is used to operate the data update.

let express = require('express');
let router = express.Router();

let mongoose = require('mongoose');
let People = require('.. /models/peopleModel');

router.post('/'.function(req, res, next){
  const _id = req.body._id,
    name = req.body.name,
    age = req.body.age,
    sex = req.body.sex,
    class = req.body.class;

  const updateFields = {
    _id,
    name,
    age,
    sex,
    class
  };
  // Update the specified reference field with the _id
  People.findByIdAndUpdate({_id, _id}, updateFields, (err, data) => {
    if(err){
      res.status(500).json({ error: err });
    }else{
      res.json({ code: 1.data: data })
    }
  });
});

module.exports = router;
Copy the code

4. Delete data

Data deletion involves the deletion of a single piece of data and batch deletion. Different deletion functions can be realized by flyers of AN ID character or an ARRAY of ID strings, requiring the use of the $in conditional operator and remove() method.

let express = require('express');
let router = express.Router();

let mongoose = require('mongoose');
let People = require('.. /models/peopleModel');

router.post('/'.function(req, res, next){
  let ids = req.body._id;
  let condition;
  if(Array.isArray(ids)){
    condition = {
      _id: { $in: ids }
    }
  }else{
    condition = {
      _id: ids
    }
  }

  People.remove(condition, (err, data) => {
    if(err){
      res.status(500).json({ error: err });
    }else{
      res.json({ code: 1.data: data })
    }
  })
});

module.exports = router;
Copy the code

So far, Mongoose has realized the operation cases of adding, deleting, checking and modifying MongoDB. I believe that you will have a good introduction to the operation of MongoDB.