Node.Js with Mongodb

Node.Js with Mongodb

NODE.JS WITH MONGODB + 1) Log into github and create a new repository Copy the github repo url you just created: 2) Navigate to the directory that will contain your new project directory and open a new git bash window there. 3) Type npm init in order to create a new node project. It will prompt you for a bunch of answers so that it can go off and generate a package.json application description file for you that specifies your application dependencies. Here are appropriate answers for this project. Type your name instead of mine obviously and your git repo url rather than mine. 4) express is a very simple node web server that will enable us to respond to our simple requests appropriate. Install it by running the following command which tells node package manager (npm) to download and install express-generator “globally” (that’s the –g). npm install –g express-generator 5) Lets use the express generator we just installed to create a skeleton project with a single command express --view=ejs api-voting 6) That created a subdirectory that contains our skeleton project. Let’s navigate into the new directory. cd api-voting 7) Open the directory we just created in your favorite development text editor (probably with a file/open folder menu click). 8) Now let’s install some other node packages (components that add features to our application). The package.json file is an inventory of all dependencies/components that your application needs to run. The-–-save parameter in a flag/parameter that tells npm to not only install the package for your application but also add the dependency to your package.json file as a dependency to remember. This is important because this list of dependencies will be used to install those bits of code on other computers, most importantly the eventual Internet server you use for deployment to share with others. The body-parser will enable your node web server application to parse FORM data into data that can be used by your web server actions. The mongoose package is a component that is designed to make it easy for us to send and receive data to a MongoDB non-relational database. npm install --save body-parser npm install --save mongoose 9) Let’s go create a database to put our data in. Go to https://www.mongodb.com/cloud and create a free account by clicking the Get Started Free button in the middle of the screen. 10) Enter your desired account details. 11) Click the Continue button and you’ll be presented with a bunch of cluster config options. We’re going to accept the defaults on the first screen by clicking the following button. 12) The default “tier” in the next panel will be FREE, what we want, so accept the default and click this button. 13) Accept the defaults on this panel too and click this button. 14) Finally, be sure to enter your cluster name and then click the Create Cluster button. 15) Click the Security tab and add a user account that you’ll use to connect. Choose a good username and click the Autogenerate Secure Password to generate a good, secure password. Leave the permissions for this user as Read and write to any database and then click the Add User button. Copy/paste and save this password somewhere as we’re going to need it in a minute. 16) Lets get our database connection details. Click back over on the Overview tab and then click the Connect button. Click the Add Current IP Address button and then the Save button that is displayed. Remember where this whitelist button is. We will also need to add our Internet server’s ip address here when we deploy to the Internet. 17) Click the Connect to your Application button and then the “I am using driver 3.4 or earlier” button to display the connection details we’ll need from our node app. Click the COPY button. Paste into a text editor and replace the <PASSWORD> bit with your real database user’s password. We’re going to use this in a minute by giving it to our node application so it knows where its database is. 18) Let’s create the collections we’ll need to hold our data. To do so we’ll need to download and use an application whose purpose in life is to enable developers to manage their MongoDB data. Click the Connect button again on your cluster and then the Connect with MongoDB Compass button and then the Operating System button to download and install the application. 19) While it’s downloading click the COPY button to capture the connection details you’ll need. 20) When the MongoDB Compass application loads it should detect the value in the connection string and put the necessary values in the required boxes for you. You’ll just need to enter the password for the database user. Click Create Favorite, Save Favorite and then Connect. 21) Now let’s create a database with the collections we’ll need for our simple app. Mongo needs an initial collection to be created with the database container so we’re going to create our database named api_votes and our first collection named api here: 22) Now let’s create 2 more collections named voter and vote. To do so click the database name… …and then click the Create Collection button. 23) We’ve downloaded and installed packages that we need for node and created a database with a couple of collections in MongoDB but we haven’t told our application to make use of them. Go back to your text editor showing you the node application directory. The app.js file located in your application root directory is what node will run to start up your application. This is most often where application setup and configuration occurs in node. Let’s modify the default lines in the file to include our new body-parser and mongoose components by adding or modifying the highlighted lines here. The red, highlighted text below is from step 17 above. var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // reference our body parser component var logger = require('morgan'); // this is the start of our MongoDB database connectivity, the next lines tell // our app where our database is, our security credentials and generally // how to speak with the database var mongoose = require('mongoose'); // paste this path from your MongoDB cloud account info panel var mongoDBPath = 'mongodb://some-user:some-user-password@empower18-ws1-shard-00-00- pgyeb.mongodb.net:27017,empower18-ws1-shard-00-01-pgyeb.mongodb.net:27017,empower18-ws1- shard-00-02-pgyeb.mongodb.net:27017/api_votes?ssl=true&replicaSet=empower18-ws1-shard- 0&authSource=admin&retryWrites=true'; dbOptions = { keepAlive: 1000, connectTimeoutMS: 30000, native_parser: true, auto_reconnect: false, poolSize: 10 }; mongoose.connect(mongoDBPath, dbOptions); mongoose.Promise = global.Promise; const db = mongoose.connection; db.on('error', (err) => { console.log(err); }); db.once('open', (err) => { if (err) { console.log(err); } }); // this file contains the default page that will be sent back upon a request var indexRouter = require('./routes/index'); // this was just an example route, we can comment it out // var usersRouter = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); // we're going to comment out the default express processor and // tell it to use our slightly better body parser instead // app.use(express.json()); // app.use(express.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); // comment out this path, no longer relevant // app.use('/users', usersRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; 24) Lets go add our application specific functionality. We need to create object definitions to mirror each of our record types. These are called “models”. Add a directory under your application root called models and add a file named voter.js within it that contains the following code. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Voter = new Schema({ first_name : String, last_name : String, username : String }, { collection: 'voter' }); module.exports = mongoose.model('Voter', Voter); 25) Create a file named api.js within that same models directory that contains the following code. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Api = new Schema({ name : String }, { collection: 'api' }); module.exports = mongoose.model('Api', Api); 26) Now create a file named vote.js within that same models directory that contains the following code. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Vote = new Schema({ voter_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Voter' }, api_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Api' } }, { collection: 'vote' }); module.exports = mongoose.model('Vote', Vote); 27) Let’s add some basic logic to make the application features meet our needs. Open routes/index.js and add/modify to the following. We will discuss this in class in detail. var express = require('express'); var router

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    16 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us