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

CRUD Update Error Mongoose Node

I am trying to update my database through my form, but when I submit the form the id I am trying to update does not update. Instead, the first item in my database is updated.

This is my code.

doctype html
head
    meta(charset='utf-8')
    meta(name='viewport' content='width=device-width, initial-scale=1.0')
    title Superb Grocery IS
    link(rel='stylesheet' type="text/css" href='stylesheets/style.css')
    script(type='text/javascript' src='javascripts/validate.js')
.main-nav
    ul.nav
        li.name Superb Grocery IS
        li
            a(href='index') Home
        li
            a(href='listing') Listing
        li
            a(href='entry') Add
        li
            a(href='update') Update
        li
            a(href='delete') Delete
header
    #wrapperr
        h1(align='center' style='color:blueviolet') Update Products
        form(name='form3' action='/updated'  method='post' style='margin-top: 20px')
            input(name='_method', value='PUT', type='hidden')
            table#table2(align='center' border='3')
                tr
                    td
                        label(for='entry_id') ID:
                    td
                        input#entry_id(type='text' name='id_name' pattern='^[a-zA-Z][a-zA-Z0-9-_\.]{5}$' placeholder='RWS35O' onblur='alphanumeric(this)' required='')
                tr
                    td
                        label(for='entry_product') Product:
                    td
                        input#entry_product(type='text' name='product_name' onblur='letpattern(this)' required='')
                tr
                    td
                        label(for='entry_price') Price:
                    td
                        input#entry_price(type='text' name='price_name' placeholder='9999 OR 9999.99' onblur='price(this)' required='')
                tr
                    td
                        label(for='entry_quantity') Quantity:
                    td
                        input#entry_quantity(type='text' name='quantity_name' placeholder='9999' onblur='numeric(this)' required='')
                tr
                    td(colspan='2' align='center')
                        button.reset(type='reset' value='Reset') Reset
                        button.update_btn(type='submit' value='Submit') Update
footer
    p#copy © 2018 SuperbGroceryIS.com

And my Javascript

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDB');
var dbSchema = mongoose.Schema({
    objID : String,
    productName : String,
    price : String,
    quantity: Number
});
var Document = mongoose.model('Document', dbSchema);

app.get('/update', function(req, res,) {
    res.render('update', { title: 'Express' });
});

app.post('/updated/',
    function(req, res) {
            Document.update({
                objID : req.body.id_name,
                productName : req.body.product_name,
                price : req.body.price_name,
                quantity: req.body.quantity_name
            }, function(err, obj) {
                if (!err) {
                    res.redirect('/update');}
                else {
                    res.send(err)
                }
            });
        });

I have also tried

app.post('/updated/',
    function(req, res) {
var id = req.params.objID;
        Document.findByIdAndUpdate(id,
            req.body, function(err, obj) {
                if (!err) {
                    res.redirect('/update');}
                else {
                    res.send(err)
                }
            });
        });

and

app.put('/updated',
    function(req, res) {
        Document.findOneAndUpdate({objID: req.params.objID}, req.body, {new: true},
            (err, obj) => {
                if (!err) {
                    res.redirect('/update');
                }
                else {
                    res.send(err)
                }
            });
    });

If anyone can assist me with the proper update code I would appreciate it.

2 Answers

Jesus Mendoza
Jesus Mendoza
23,289 Points

You don't have any parameters in your post url, so the value of req.params.objID is undefined and when you try to findByIdAndUpdate the value of the variable id is undefined

app.post('/updated/',
   function(req, res) {
      var id = req.params.objID; // this value here is undefined.
      Document.findByIdAndUpdate(id,
         req.body, function(err, obj) {
            if (!err) {
               res.redirect('/update');}
            else {
               res.send(err)
            }
   });
});

In order to have access to req.params.objID your route should have and endpoint like this

app.post('/updated/:objID', // now you have the param objID in your route
   function(req, res) {
      var id = req.params.objID; // this value is now defined when you access /updated/012U398QWE82.
      Document.findByIdAndUpdate(id,
         req.body, function(err, obj) {
            if (!err) {
               res.redirect('/update');}
            else {
               res.send(err)
            }
   });
});

Thanks Jesus, you are the greatest!