Nodejs Learning Note two link MongoDB

Source: Internet
Author: User
Tags install mongodb

A. Installing the Mongoose Library to link the MongoDB database

Installing MongoDB Database Reference MongoDB installation

  Preface (complaint)

Originally wanted to install MongoDB library to link MongoDB, command line to nodejs Project catalog: NPM Install MongoDB--save

  

But Discovery reported gyp err! stack error:can ' t find python executable "python" error, missing python runtime environment.

I fainted, I link MongoDB also need python, this is not intentionally let users find abuse. Found that there is a netizen said the same library and mongoose, Mongoskin, they are more useful than MongoDB. Decisively abandon MongoDB, using Mongoos.

Using the command: NPM install Mongoose--save

  

It's OK.

Use of B.mongoose

First of all we need to know that mongoose to build a database a bit like normal relational data first define the structure, and then fill in the fields, do not want ordinary NoSQL database operation. So here are some concepts that need to be understood

    • Schema: A database model skeleton stored as a file, not capable of database operation

    • Model: The Schema model generated by the publication, database operations with abstract properties and behaviors

    • Entity: by Model Creating an entity, his actions also affect the database

When you use Mongoose to build and manipulate a database, you define the structure of each data in the database (a row in a normal relational database), which is the schema, and then the schema generates a model. This model has the ability to manipulate the data in the entire table consisting of the schema structure (including additions, deletions, etc.). Entity data can be created by model one by one, with the same structure for each entity's data structure and schema definition.

Directly below the example

//record BooksvarPocketbookschema =NewMongoose. Schema ({name:string,//defines an attribute name, which is of type stringBrand:string,//BrandUnitprice:number,//Unit PriceQuantity:number,//QuantityAllprice:number,//Total PricePicture:string,//Photo PathDate:string,//Date "2016-01-01"_savedata:date,//date The data was savedRemark:string//Notes});varPocketbookmodel = Db.model (' pocketbook '), Pocketbookschema);//If the model has been published, it can be indexed directly by name, as follows://var Pocketbookmodel = Db.model (' pocketbook ');varinfo ={name:req.body.name, Brand:req.body.brand, UnitPrice:req.body.unitPrice, Quantity:req.body.quantity, AllPrice:req.body.allPrice, Picture:req.body.picture, Date:req.body.date, Remark:req.body.remark, _save Data:NewDate ()}//Create an instancePocketbookentity =NewPocketbookmodel (info);//Save DatabasePocketbookentity.save (function(err) {if(Err) {Console.log (' bookkeeping adds a data failure '); return; } console.log (' Bookkeeping adds a piece of data ');});

The above is an example of using mongoose to add a piece of data, of course, the real project also need to connect to the MongoDB database, and then delete the changes are processed through the URL request. I am here to give a complete example.

My Nodejs main program is server.js, under the same level directory I created a new initdb.js used to link the database and initialize all the requiredSchema和相应的model(这里只用了一个).

Initdb.js source code is as follows

varMongoose = require (' Mongoose ');//referencing the Mongoose modulevardb = Mongoose.createconnection (' 192.168.0.174 ', ' chuayyqing '); Db.on (' Error ', Console.error.bind (console, ' connection error: ')));//record BooksvarPocketbookschema =NewMongoose. Schema ({name:string,//defines an attribute name, which is of type stringBrand:string,//BrandUnitprice:number,//Unit PriceQuantity:number,//QuantityAllprice:number,//Total PricePicture:string,//Photo PathDate:string,//Date "2016-01-01"_savedata:date,//date The data was savedRemark:string//Notes});varPocketbookmodel = Db.model (' pocketbook '), Pocketbookschema);//If the model has been published, it can be indexed directly by name, as follows://var Pocketbookmodel = Db.model (' pocketbook ');Exports.pocketbookmodel= Pocketbookmodel;

Server.js as follows

  

varExpress = Require ("Express");varApp =Express ();varBodyparser = require (' Body-parser '));//creating application/x-www-form-urlencoded Encoding parsingvarUrlencodedparser = bodyparser.urlencoded ({extended:false })varModels = require ("./initdb");//specifies static file path strength static, you can directly access the file under static Test.png:http://localhost:8080/test.pngApp.use (express.static (' chuayyqing/static ')));//Check the list of bookkeepingApp.get ("/pocketbook-list",function(req,res) {Models.pocketBookModel.find (function(err,pockets) {res.send (pockets); })})//add a record to the bookkeepingApp.post ("/pocketbook-addorupdateone", Urlencodedparser,function(req,res) {/*info = {name:req.body.name, Brand:req.body.brand, UnitPrice:req.body.unitPrice, Quanti        Ty:req.body.quantity, AllPrice:req.body.allPrice, Picture:req.body.picture, Date:req.body.date,    Remark:req.body.remark, _savedata:new Date (); }*/    varinfo =Req.body; Info._savedata=NewDate (); Console.log (Info)//there is _id to change a piece of data    if(info._id) {varquery ={_id:req.body._id}; Models.pocketBookModel.findOneAndUpdate (Query,info,function(err) {if(Err) {Console.log (' Bookkeeping changes a data failure '); Res.send ({code:500}); return} console.log (' Account book modified a piece of data '); Res.send ({code:200});    }); //otherwise a new piece of data}Else{        //if not published, the previous code will be an exception        varPocketbookentity =NewModels.pocketbookmodel (info); //Save DatabasePocketbookentity.save (function(err) {if(Err) {Console.log (' bookkeeping adds a data failure '); Res.send ({code:500}); return; } console.log (' Bookkeeping adds a piece of data '); Res.send ({code:200});    }); }    })//Delete a record of an accounting bookApp.post ("/pocketbook-deleteone", Urlencodedparser,function(req,res) {models.pocketBookModel.remove ({_id:req.body.id},function(err) {if(Err) {Console.log (' Accounting for this delete data failed '); Res.send ({code:500}); return; } console.log (' Bookkeeping deleted a piece of data '); Res.send ({code:200}); })})varServer = App.listen (8080,function(){    varHost =server.address (). Address; varPort =server.address (). Port; Console.log ("Application instance, Access address is http://%s:%s", host, Port)})

Additions and deletions to the number of operations above all have. Just a few simple pages to get server.js to run.

Inside Express usage can refer to the Beginner Tutorial Expres Foundation

  If you feel this article is good, please click on the bottom right "recommended"!

  

  

  

Nodejs Learning Note two link MongoDB

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.