Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo Sessions and Cookies Creating the Profile Route and Page

Juliette Tworsey
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Juliette Tworsey
Front End Web Development Techdegree Graduate 32,425 Points

Change favorite book on profile page

Hi,

I have managed to change the title of my user's favorite book in the database via the shell like so:

db.users.update({_id:ObjectId("5898e0659946de61e3e3e698")},{$set:{favoriteBook:"Guns Germs and Steel"}})

..but I have not been able to figure out how to do this on the front end via the profile page via a new form submission along with a new router.put request in the routes/index.js file:

router.put('/profile', function(req, res, next) {


        User.findById(req.params.userId, function(err, User) {

            if (err)
                res.send(err);

            User.favoriteBook = req.body.favoriteBook;  // update the Users info


            User.save(function(err) {
                if (err)
                    res.send(err);

                return res.render('profile', { favorite: user.favoriteBook });
              //  res.json({ message: 'User updated!' });
            });

        });


    });

I'm wondering if I'm on the right track. I would really love to figure out how to do this.

Thanks in advance to anyone who can help:-)

3 Answers

Seth Kroger
Seth Kroger
56,413 Points

You're mostly on the right track. The trouble is when submitting a form, browsers only use GET and POST. You can fake a PUT, but you need an additional piece of Express middleware called method-override and some extra bits in the form to do it.

Also, if I remember the project correctly, isn't the user id under req.session instead of req.params?

Juliette Tworsey
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Juliette Tworsey
Front End Web Development Techdegree Graduate 32,425 Points

Hi again Seth!

I am so stoked right now!

Thanks to your advice I can now update the profile user's favorite book (and I added a favorite band) on the user profile page. The updates are now appearing on both the profile page AND in the mongo shell/database. I have installed the method-override middleware as you have suggested and made a few adjustments like so:

//app.js
var methodOverride = require('method-override');
var app = express();
         //profile.pug

          form(method='POST' action='/profile?_method=PUT')
              div.form-group
                label(for='favoriteBook') Favorite Book:
                input#favoriteBook.form-control(type='text', placeholder='title of book' name='favoriteBook')
              div.form-group
                label(for='favoriteBand') Favorite Band:
                input#favoriteBand.form-control(type='text', placeholder='favorite band' name='favoriteBand')

             button.btn.btn-primary(type='submit') Update Preferences
//routes/index.js

var methodOverride = require('method-override');

router.post('/profile', function(req, res, next) {


        User.findById(req.session.userId, function(err, User) {

            if (err)
                res.send(err);

            User.favoriteBook = req.body.favoriteBook;  // update the user info
            User.favoriteBand = req.body.favoriteBand;
            // save the new user info
            User.save(function(err) {
                if (err)
                    res.send(err);

                return res.render('profile', { favorite: User.favoriteBook, band: User.favoriteBand });
              //  res.json({ message: 'User updated!' });
            });

        });


    });

Wow! I was starting to think that I was in over my head (I do need to go back and understand Express and Pug a bit more) and I was about to put off trying to figure this out for awhile. This has helped to deepen my understanding of Express.js and MongoDb in a big way.

Thanks again:-)

Juliette Tworsey
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Juliette Tworsey
Front End Web Development Techdegree Graduate 32,425 Points

Hi Seth,

Thanks for responding. You are correct in pointing out that the user id under req.session. That was an oversight on my part after trying out a few different hacks.

I initially had "post" on the form submission, but when that failed to work I decided to try "put" (must have been my subconscious mind telling me to troubleshoot in Postman). I am going to have to check out the method-override middleware that you have mentioned and change req..params to req.session and see where it gets me.

Thanks!