Mongodb data types and mongoose common Curd_mongodb

Source: Internet
Author: User
Tags mongodb mongodb interface object model regular expression jquery library

Objective

After watching the node.js actual combat, which in the data storage part of the Redis, Mongodb, I also wrote the book according to the introduction of a few simple demo, in the demo process first encountered the problem is the type of data and common curd writing. There are two ways to mongodb common operations, one is to use the API directly, and the same is that you use T-SQL to write SQL statements to manipulate the data, and then use the Mongoose driver in the program to manipulate the data. It's equivalent to using ado.net or EF to manipulate data in a program, and if you've already written several demo calls to the API, then I suggest looking back at the Mongoose API, looking at the API, and remembering common methods like Where,skip,sort, etc.

As we've written the web in the past, we're concerned about the skills of data from the client (views) to the controller layer, and then how the data is passed from the controller layer to the DAO layer and the two levels that pass the data, so the thinking is applicable in node.

What is MongoDB?

MongoDB is an open source NoSQL database, compared to MySQL-like relational database, it is more lightweight, flexible, very suitable for data in a large scale, transactional not strong occasions to use.

Mongoose

Mongoose is an object model library that encapsulates MongoDB operations and is born for Nodejs. It's as if we think native JavaScript is difficult to write, and the amount of code is much, so we use the jquery library, because the MongoDB interface is complicated and inhuman, so we have mongoose. This library is entirely optional.
Mongoose is very simple to use, add mongoose to dependence in the app's Package.js, and then NPM install.

MongoDB data type

1, NULL. {' x ': null}.

2, Boolean. {' X ': true}, {' X ': false}.

3, data type. 64-bit floating-point data is used by default in the MongoDB shell, such as {"X": 2.32}, {"X": 2}, and {"X": Numberint (2)}, {"X": Numberlong (2)} If you want to use an integer type.

4, String. The string in MongoDB is encoded in UTF-8, {"x": "Hello World"}.

5, Date type. {"X": New Date ()}.

6, regular expression. The same regular expression {"X":/itbilu/i} as JavaScript can be used in MongoDB.

7, data. The use of arrays in MongoDB is the same as JavaScript {"x": ["Hello", "World"]}.

8, embedded documents. {"X": {"Y": "Hello"}}.

9, ID and Objectid (). MongoDB Each document contains a _id, and MongoDB automatically generates a Objectid object if you do not specify it.

10, code. {"X": function AA () {}}.

11, binary system.

Common curd

var mongoose=require (' Mongoose '); var schema=mongoose.
Schema;
1, the connection string mongoose.connect (' mongodb://localhost/test ');
  2. Define your data model (that is, the table we defined in the relational database) var todoschema=new Schema ({title:string, finished:{type:boolean,default:false},
Post_date:{type:date,default:date.now}});
3. Access Todo 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);
}
  }); ///Find separate data var findtodobyid=exports.findtodobyid=function (id,callback) {Todo.findone ({_id:id},function (Err,doc) {/
    /doc is the record value if (ERR) {callback (Err,null) that is based on the ID;
  } callback (Null,doc); }//Remove Exports.delete=function (id,callback) {Exports.findtodobyid (Id,function (Err,doc) {if (err) {callback (E
    RR);
      }else{Doc.remove ();
    callback (NULL); }}//Edit 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 are ways to write this directly: Var m=this;
  var start= (pageIndex-1) *pagesize;
  M.skip (start);
  M.limit (pageSize); M.sort ({' Post_date ', ' ASC '});
  Sort///According to the keyword query after pagination//m.where (' title ', ' XXX ');
    Performs a paging query M.exec (ERR,RS) {//pagination result if (err) {callback (ERR);
        }else{Todo.find (function (err,result) {/* * Normal paging you need to return both the total number of database records and the data after pagination, so here is a todo.find query once
      * * Callback ({rows:rs,total:result.length});
    }); }
  })
}

The above content is small series to introduce the MongoDB data types and mongoose commonly used curd, I hope you like.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.