Mongodb data types and Mongoose commonly used CURD

  • 2020-05-15 02:29:06
  • OfStack

preface

After reading Node and js, I mentioned Redis and Mongodb in the data storage section. I also wrote some simple demo according to the introduction in the book. The first problem I encountered in the process of demo was data type and common CURD writing. mongodb common operation there are two ways, one is the direct use of API, also is the equivalent of you in SQL Server clients use T - SQL write SQL statements to manipulate the data sample 1, the second is using mongoose driver to manipulate the data in the program, equivalent to in the process we use ADO. NET or EF to manipulate data, if you have already written a few calls API demo, then I suggest return overdo to see mongoose API again, Look at API and remember several common methods such as where,skip,sort, etc

In the way we used to write Web, we looked at how data from the client side (Views) went to the Controller layer, and then passed the data from the Controller layer to the Dao layer, and some of the tricks that were used to transfer the data from the Controller layer to the Dao layer, and this is also true in Node.

What is MongoDB?

MongoDB is an open source NoSQL database. Compared with relational databases like MySQL, MongoDB is more lightweight and flexible. It is very suitable for large data scale and non-transactional situations.

Mongoose

Mongoose is an object model library that encapsulates the operations of MongoDB and is created for nodejs. As if native javascript is too hard to write and too much code, we use jQuery library 1, because MongoDB's operation interface is complex and inhuman, so we have Mongoose. This library is completely optional.
The use of Mongoose is very simple. mongoose is added to dependence of App, package.js, dependence, and npm install.

Mongodb data type

1, null. {" x ": null}.

2, Boolean. {" x ": true}, {" x" : false}.

3. Data type. In Mongodb Shell, 64-bit floating point data is used by default, such as {"x":2.32}, {"x":2}, or {"x":NumberInt(2)}, {"x":NumberLong(2)}, if you want to use integer types.

4. String. Strings in Mongodb are encoded in UTF-8, {"x":"hello world"}.

5. Date type. {" x ": new Date ()}.

6. Regular expressions. The same regular expression {"x":/itbilu/i} can be used in Mongodb.

7. Data. The use of arrays in Mongodb is the same as in javascript {"x":["hello","world"]}.

8. Embedded documents. {" x ": {" y" : "Hello"}}.

9, Id and ObjectId(). Each Mongodb document contains one _id, and Mongodb automatically generates one ObjectId object if you do not specify it.

10. Code. {" x ": function aa () {}}.

11, base 2.

Common CURD


var mongoose=require('mongoose');
var Schema=mongoose.Schema;
//1 , connection string 
mongoose.connect('mongodb://localhost/test');
//2 Define your data model ( That's what we define in a relational database Table)
var TodoSchema=new Schema({
  title:String,
  finished:{type:Boolean,default:false},
  post_date:{type:Date,default:Date.now}
});
//3 , access, todo The object model 
mongoose.model('Todo',TodoSchema);
// add 
exports.add=function(title,callback){
  var newTodo=new Todo();
  newTodo.title=title;
  newTodo.save(function(err){
    if(err){
      console.log(err);
      callback(err);
    }else{
      callback(null);
    }
  });
}
// Look for individual data 
var findTodoById=exports.findTodoById=function(id,callback){
  Todo.findOne({_id:id},function(err,doc){
    //doc That is based on id The resulting record value 
    if(err){
      callback(err,null);
    }
    callback(null,doc);
  })
}
// delete 
exports.delete=function(id,callback){
  exports.findTodoById(id,function(err,doc){
    if(err){
      callback(err);
    }else{
      doc.remove();
      callback(null);
    }
  })
}
// Edit the title 
exports.editTitle=function(id,title,callback){
  exports.findTodoById(id,function(err,doc){
    if(err){
      callback(err);
    }else{
      doc.post_date=new Date();
      doc.title=title;
      doc.save(function(err){
        if(err){
          callback(err);
        }else{
          callback(null);
        }
      })
    }
  })
}
exports.allTodos=function(callback){
  Todo.find({},callback);
}
// Paging query 
exports.TodoPageList=function(pageIndex,pageSize,callback){
  var m=Todo.find({}); // There's a way to write it like this : var m=this;
  var start=(pageIndex-1)*pageSize;
  m.skip(start);
  m.limit(pageSize);
  m.sort({'post_date','asc'}); // The sorting 
  // Pagination after query by keyword 
  //m.where('title','XXX');
  // Performing paging queries 
  m.exec(function(err,rs){
    // Results after paging 
    if(err){
      callback(err);
    }else{
      Todo.find(function(err,result){
        /*
          1 Normally for paging you need to return both the total number of database records and the paged data, so this is used Todo.find The query again 1 time 
        */
        callback({rows:rs,total:result.length});
      });
    }
  })
}

The above content is the Mongodb data type and Mongoose commonly used CURD introduced by this site, I hope you like it.


Related articles: