Save node. JS data to the MONGO database

Source: Internet
Author: User
Tags findone http 200 mongodb driver

Mongo Database Installation

First to Mongo's official website to download the installer: http://www.mongodb.org/, I downloaded the file name is: Mongodb-win32-x86_64-2008plus-2.6.4-signed.msi

Executes the setup program.

Next

Agree to the license agreement

You can choose customize custom to see.

Put it all on.

Start the actual installation.

MongoDB is installed by default in the C:\Program files\mongodb 2.6 Standard\bin directory, but it is not automatically added to the path path and is added manually.

Directly execute Mongod startup database, receive the following information, the original to specify the location of the database file.

PS \> Mongodc:\program Files\mongodb 2.6Standard\bin\mongod.exe--help for help and startup options2014-09-13t11:24:01.755+0800 [Initandlisten] MongoDB starting:pid=42300 port=27017 dbpath=\data\db\ 64-bit host=openxlive2014-09-13t11:24:01.755+0800 [Initandlisten] targetminos:windows 7/windows Server 2008r22014-09-13t11:24:01.755+0800 [Initandlisten] db version v2.6.42014-09-13t11:24:01.755+0800 [Initandlisten]Git version:3a830be0eb92d772aa855ebb711ac91d658ee9102014-09-13t11:24:01.755+0800 [Initandlisten] Build Info: Windows Sys.getwindowsversion (major=6, Minor=1, build=7601, platform=2, service_pack= ' Service Pack 1 ') boost_lib_ version=1_492014-09-13t11:24:01.755+0800 [Initandlisten]allocator:system2014-09-13t11:24:01.755+0800 [Initandlisten]Options: {}2014-09-13t11:24:01.770+0800 [Initandlisten] exception in initandlisten:10296Error:dbpath (\data\db\) does not exist. Create This directory or give the existing directory in--dbpath. See http://dochub.mongodb.org/core/startingandstoppingmongo**************************************************** *****************,terminating2014-09-13t11:24:01.770+0800 [Initandlisten] dbexit:2014-09-13t11:24:01.770+0800 [ Initandlisten] shutdown:going to close listening sockets ... 2014-09-13t11:24:01.786+0800 [Initandlisten] shutdown:going to flush Diaglog ... 2014-09-13t11:24:01.786+0800 [Initandlisten] shutdown:going to close sockets ... 2014-09-13t11:24:01.786+0800 [Initandlisten] shutdown:waiting for FS preallocator ... 2014-09-13t11:24:01.786+0800 [Initandlisten] shutdown:lock for final commit ... 2014-09-13t11:24:01.786+0800 [Initandlisten] shutdown:final commit ... 2014-09-13t11:24:01.786+0800 [Initandlisten] shutdown:closing All Files ... 2014-09-13t11:24:01.786+0800 [Initandlisten] closeallfiles () finished2014-09-13t11:24:01.786+0800 [ Initandlisten] dbexit:really exiting           now

Create a folder to save the database files, use--dbpath to start, success.

Mongod--dbpath C:/mysite/mongodb

Reopen a command window and enter the command line MONGO start MONGO.

PS c:\mysite> mongomongodb shell version:2.6.4connecting To:testwelcome to the MongoDB shell. For interactive help, type ' help '. For more comprehensive documentation, see        http://docs.mongodb.org/Questions? Try the Support group        http://groups.google.com/group/mongodb-user>    

First, we create a database to hold our user information, and the name of the database is called the members.

Use Members

Very much like SQL Server, if you do not have this database, you will create this database immediately.
Use show DBS to see which databases are available.

Create a collection in this database named users, and insert a user information. There is currently no users collection, and MongoDB creates it directly.

> Db.users.insert ({"UserId": 1, "name": "Tom", "email": "[email protected]"})

Find information can use Find or findOne, except that FindOne returns only one result.

Db.users.findOne ({"UserId": 1})

Results returned:

{        "_id": ObjectId ("5413be6e9e1c9f9c4386756d"),        "UserId": 1,        "name": "Tom",        "email": "[email Protected] "}
Driver Program

Edit Package.json to add a reference to MongoDB.

{    "name": "Express-api",    "version": "0.0.1",    "dependencies": {        "Express": "2.5.9" ,        "Ejs": "0.4.2", "MongoDB": "1.4.1" }}     

Re-install the MongoDB driver for NPM installation.
The output is as follows:

PS c:\mysite> npm installnpm WARN package.json [email protected]No descriptionnpm WARN Package.json [email protected]No repository field.npm WARN Package.json [email protected]No README datanpm WARN package.json [email protected]No Repository field.npm http GET https://registry.npmjs.org/mongodbnpm http 304HTTPS://REGISTRY.NPMJS.ORG/MONGODBNPM http GET https://registry.npmjs.org/mongodb/-/mongodb-1.4.1. TGZNPM http https://registry.npmjs.org/mongodb/-/mongodb-1.4.1. TGZNPM http GET https://registry.npmjs.org/bsonnpm http GET https://registry.npmjs.org/kerberosnpm HTTP 200HTTPS://REGISTRY.NPMJS.ORG/KERBEROSNPM http GET https://registry.npmjs.org/kerberos/-/kerberos-0.0.3. TGZNPM HTTP 200HTTPS://REGISTRY.NPMJS.ORG/BSONNPM http GET https://registry.npmjs.org/bson/-/bson-0.2.7. TGZNPM http https://registry.npmjs.org/kerberos/-/kerberos-0.0.3. TGZNPM http https://registry.npmjs.org/bson/-/bson-0.2.7.tgz> [email protected] Install c:\mysite\node_modules\mongodb\node_modules\kerberos> (node-gyp rebuild 2> builderror.log) | | (Exit 0) C:\mysite\node_modules\mongodb\node_modules\kerberos>node "c:\nodejs\node_modules\npm\bin\node-gyp-bin\ \.. \.. \node_modues\node-gyp\bin\node-gyp.js " rebuildnpm http GET https://registry.npmjs.org/nannpm http https:/ /REGISTRY.NPMJS.ORG/NANNPM http GET https://registry.npmjs.org/nan/-/nan-0.8.0. TGZNPM http https:// registry.npmjs.org/nan/-/nan-0.8.0.tgz> [email protected] install C:\mysite\node_modules\mongodb\node_ Modules\bson> (Node-gyp rebuild 2> builderror.log) | | (Exit 0) C:\mysite\node_modules\mongodb\node_modules\bson>node "c:\nodejs\node_modules\npm\bin\ node-gyp-bin\\. \.. \node_modules\ode-gyp\bin\node-gyp.js " rebuild[email protected] Node_modules\mongodb├──[email protected] └──[email protected] ([email protected]) PS c:\mysite>          
Using the MongoDB database

Modify the code, first require the MongoDB module, and then connect to the MongoDB database.

var MONGO = require ("MongoDB") var Express = require ("Express"); var app =Express.createserver (); App.set ("View Engine", "Ejs"); App.set ("views", __dirname + "/views"); App.set ("View Options", {Layout:false}); App.get ("/", function  (request, Response) {Response.render ("index" );}); App.get ("/user/:id", function  (request, response) {var id =  request.params.id; console.log (ID); App.users.findOne ({"UserId": +id}, function  (Error, doc) {if (error) return  next (error); Response.json (DOC) ; });});/ /Connect mongodb var server = new MONGO. Server ("127.0.0.1", 27017 ); var db = new MONGO. Db ("Members", Server, {safe:true}). Open (function  (error, client) {if (error) throw  error; Console.log ("\033 [96m + \033[39m connected to MongoDB ' ]; app.users = new MONGO. Collection (Client, "users" ); Client.ensureindex ("Users", "UserId", function  (error) {if (error) throw  error; Console.log ("\033[96m + \033[39m ensured index." ); Console.log ("Web Server listening ..." ); App.listen (+ );});               


Note Now that you are looking for users in the database. The + in front of the ID is used to convert the string type data in the form to the number type we need.

App.users.findOne ({"UserId": +id}, function (Error, doc) {        if (Error) return next (error);        Response.json (DOC);    }); 

Save node. JS data to the MONGO database

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.