Home > mongodb, nodeJS, NOSQL > Node js Web application Development Part 3

Node js Web application Development Part 3

Here is the sourcecode for the project : https://github.com/supun/NodeExpress

Writing to the database is not particularly difficult. Essentially we need to set up a route that takes a POST, rather than a GET. We could use AJAX here, and honestly that’s my preference most of the time … but that’s really a whole different tutorial, so we’ll stick to a standard post-and-show-results approach. Once again, though, it’s not too hard to adapt things to work that way if you want.

STEP 1 – CREATE YOUR DATA INPUT

We’re going quick and dirty here: two ugly, unstyled text inputs and a submit button. 1996-style. Just like before, we’ll start with app.get(); and then give it something to get. Open up app.js and find the part with all of those app.get() calls, and add this to the bottom of them:

app.get('/newuser', routes.newuser);

So that you get:

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/helloworld', routes.helloworld);
app.get('/userlist', routes.userlist(db));

// New Code
app.get('/newuser', routes.newuser);

As with all app.get requests, we need to adjust the route to know what to serve up. Open up /routes/index.js and add the following:

exports.newuser = function(req, res){
  res.render('newuser', { title: 'Add New User' });
};

Now we just need a template, as newuser.jade, and replace the whole file contents with this:

extends layout

block content
    h1= title
    form#formAddUser(name="adduser",method="post",action="/adduser")
        input#inputUserName(type="text", placeholder="username", name="username")
        input#inputUserEmail(type="text", placeholder="useremail", name="useremail")
        button#btnSubmit(type="submit") submit

Here we’re creating a form with the ID “formAddUser” (I like to preface my IDs with the type of thing we’re ID’ing. It’s a personal quirk). Method is post, action is adduser. Pretty straightforward. Under that we’ve defined our two inputs and our button.

If you restart your node server and go to http://localhost:3000/newuser you’ll see your form in all its glory.

browsershot4

Go ahead and submit. Enjoy the “can’t post to /adduser” error. We’re about to fix that.

STEP 2 – CREATE YOUR DB FUNCTIONS

OK, same process as before. First we edit app.js, then our route file, and then our Jade template. Except there’s no Jade template here because we’re posting and then forwarding. See below. It’ll all make sense! Let’s start: Open app.js and once again find your stack of app.get calls:

Now add the following at the bottom of the app.js:


app.post('/adduser', routes.adduser(db));

Note that that’s an app.post, not an app.get. If you want to separate it from the app.gets with a comment or newline, I won’t stop you. Let’s set up our route.

Go back to /routes/index.js and let’s create our insertion function. This is a big one, so I’ve commented the code pretty thoroughly. Here it is:

exports.adduser = function(db) {
    return function(req, res) {

        // Get our form values. These rely on the "name" attributes
        var userName = req.body.username;
        var userEmail = req.body.useremail;

        // Set our collection
        var collection = db.get('usercollection');

        // Submit to the DB
        collection.insert({
            "username" : userName,
            "email" : userEmail
        }, function (err, doc) {
            if (err) {
                // If it failed, return error
                res.send("There was a problem adding the information to the database.");
            }
            else {
                // If it worked, set the header so the address bar doesn't still say /adduser
                res.location("userlist");
                // And forward to success page
                res.redirect("userlist");
            }
        });

    }
}

Assuming your server is running, which it should be, return to your web browser and point it at http://localhost:3000/newuser again. There’s our exciting form, just like before. Except now let’s fill in some values before we hit submit. I went with username “noderocks” and email “noderocks@rockingnode.com” … you can go with whatever you’d like.

browsershot5

It will redirect to userslist.

browsershot6

Reference : http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

Advertisements
Categories: mongodb, nodeJS, NOSQL
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: