Hit A Snag

Daily Standup

So close with my value app!! I got it to a point where I considered the MVP just about finished and in testing the site I noticed a bug. The per-use cost would update properly whenever I added a new use, but I noticed that if I edit the initial purchase amount, the per-use cost wasn’t updating at the same time.

I realized this was because I’m using findByIdAndUpdate, using only the user input from the form to update the document, whereas the per-use-cost would also need to be calculated and updated based on the newly updated initial purchase price. I had a few ideas to try and fix this:

  • Add the current per-use-cost into the update object somehow so that it is submitted with the other form data: doesn’t work because you would still need to pull the useCount from the stored data.

  • Instead of findByIdAndUpdate, use findById to pull the existing document from the database, including the current useCount. Calculate the new useCount and create a new object containing all of the updated information. Use Model.update() to then send the new object to the database. I tried this with the code below, but the data didn’t persist. I’m still not entirely sure why so I will try to figure this out, but may move on to option 3 instead.

    UserThing.findById(req.params.id, function(err, foundThing) {
    if (err) {
    res.redirect("/mythings");
    console.log(err);
    } else {
    console.log("Step 1: " + foundThing);
    var updatedCurrentValue = req.body.purchasePrice / foundThing.useCount;
    var modifiedThing = {
    name: req.body.name,
    purchaseDate: new Date(req.body.purchaseDate),
    purchasePrice: req.body.purchasePrice,
    currentValue: updatedCurrentValue
    };
    console.log("Newly created object: " + modifiedThing);
    foundThing.update(req.params.id, modifiedThing, function(err, updatedThing) {
    if (err) {
    res.redirect("/mythings");
    console.log(err);
    } else {
    console.log("Step 2: " + modifiedThing);
    req.flash("success", "Thing updated!");
    res.redirect("/mythings/" + req.params.id);
    }
    });
    }
    });

    I don’t like this anyway because it’s really messy!

  • Option 3: it may make more sense beyond this issue to use update the values using AJAX instead of reloading the page for each update. I was already thinking this may be the best solution for deleting useDates as well. So next I’ll learn a bit about AJAX to see if it’s really a good solution.