Nodejs Learning Notes (ii)---manipulating MongoDB database

Source: Internet
Author: User

Recently read some articles about MongoDB, and then want to know how Nodejs is connected so I try to understand a wave (this rookie station this site is also good, although the knowledge of the document is not the latest, but still fine;

By the way the official address is this OH: http://mongoosejs.com/docs/guide.html

Well, let's get into today's theme:

First come into the root directory of your project to install: NPM Install Mongoose

have been wanting to use this data, and recently finally got the wish. The use of the database, I think the first is to change from adding and deleting to start, and then go like more complex to the point of the seller
First, how to get his connection.
Create db.js that can be named directly from node Db.js to see the effect of the connection
One establishes the connection
varMongoose = require (' Mongoose ')), Db_url= ' Mongodb://127.0.0.1:27017/test ';//ConnectionMongoose.connect (db_url);//test whether the connection was successfulMongoose.connection.on (' Connected ',function() {Console.log (' My MongoDB connection success!!! ')})//Case of Connection exceptionMongoose.connection.on (' Error ',function(er) {console.log (' Connection error: ' +er);})//Connection DisconnectMongoose.connection.on (' Disconnected ',function() {Console.log (' Mongogdb disconnection ')}) Module.exports= Mongoose;

Two: Create a data model
Create a schema (a bit like creating an instance property) and create a model

Get the connection var mongoose = require ('./db.js '),  Schema = Mongoose. schema;//Create user var userInfo = new Schema ({  uid: {type:string},  uname: {type:string},  upwd: {type:string},
   logindate: {type:date}})//Convert the well-defined schema to model module.exports = Mongoose.model (' UserInfo ', userInfo);

Three pairs of database operations

3.1 Insert Operation:

varUser = require ('./userinfo.js '))/*Insert Operation*/functionInsert () {varUserInfo =NewUser ({uid:' 1 ', uname:' Yaobo1 ', Upwd:' 123 ', Logindate:NewDate ()}) Userinfo.save (function(Err, res) {if(Err) {Console.log (' Err ' +err); } Else{Console.log (' Res: ' +Res)} })}insert ();
View Code

3.2 Query Operation:

In this case, we use regular expressions to judge the fuzzy query.

Reference:

use of $regex operatorsThe option options in the $regex operator can change the default behavior of the regular match, which includes the I, M, X, and S four options, which have the following meanings
    • I ignore the case, {<field>{$regex/pattern/i}}, and after setting the I option, the letters in the pattern are case insensitive.
    • M multiline matching pattern, {<field>{$regex/pattern/, $options: The ' m '},m option changes the default behavior of the ^ and $ metacharacters, respectively, by matching the beginning and end of the line, instead of matching the beginning and end of the input string.
    • X ignores non-escaped whitespace characters, {<field>:{$regex:/pattern/, $options: ' m '}, when the X option is set, the non-escaped whitespace characters in the regular expression are ignored, and the pound sign (#) is interpreted as the beginning of the note, Can only be explicitly located in the option options.
    • s single-line matching mode {<field>:{$regex:/pattern/, $options: ' s '}, setting the S option changes the number of points in the pattern (.) The default behavior of metacharacters, which matches all characters, including newline characters (\ n), can only be explicitly placed in the option options.
There are several issues to note when using the $regex operator:
    • I,m,x,s can be used in combination, for example: {name:{$regex:/j*k/, $options: "Si"}}
    • A regular match on the field where you set the bow} can increase the query speed, and the query speed is further improved when the regular expression uses a prefix expression, for example: {name:{$regex:/^joe/}
varUser = require ('./userinfo.js '))/*Query Operations*/functionFind () {Let wherestr= {uid: ' 1 '} user.find (Wherestr,function(Err, res) {if(Err) {Console.log (' Err ' +err); } Else{Console.log (' Res: ' +Res)} })}/*Fuzzy Query*/functionGetregex () {varWherestr = {uname: {$regex:/yaobo/m}} console.log (WHERESTR); User.find (Wherestr,function(Err, res) {if(Err) {Console.log (' Err ' +err); } Else{Console.log (' Res: ' +Res)} })}/*Aggregate Queries*/functionAggregate () {varWherestr = [{$group: {_id: ' $uname ', num: {$sum: 1}}] Console.log (WHERESTR); User.aggregate (Wherestr,function(Err, res) {if(Err) {Console.log (' Err ' +err); } Else{Console.log (' Res: ' +json.stringify (res))} })}//find ();//http://blog.csdn.net/u022812849/article/details/51314810//Getregex ();aggregate ();
View Code

3.3 Delete Operations

var User = require ('./userinfo.js ')function  Remove () {  = {uid: ' 1 '}    function  (er, res) {    if  (er) {      console.log (' er: ', er)    }     if  (res) {      console.log (' res ', res)    }  })}remove ();
View Code

3.4 Update Actions

var User = require ('./userinfo.js ')function  Update () {  var wherestr = {uname: ' Yaobo1 '}  var updatestr = {uname: ' Magical Creator '}  function  (er, res) { c13/>if  (er) {       console.log (' er: ', er)     }     if  ( RES) {       console.log (' res ', res)     }  })}update ();
View Code

In fact, this writing down will find that after mastering the structure, is to know how to use Nodejs to operate MongoDB, there may be some complicated did not write (follow up with good things, and then add), but the basic statement mastered, Master Mongdb language is particularly important

Nodejs Learning Notes (ii)---manipulating MongoDB database

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.