troubleshooting Question

Profile.save is not a function. What am I doing wrong?

Avatar of Bruce Gust
Bruce GustFlag for United States of America asked on
JavaScriptNode.js
11 Comments1 Solution107 ViewsLast Modified:
Here's my code in full:

require("dotenv").config();
const { validationResult } = require("express-validator/check");
const mongoose = require("mongoose");
const Profile = require("../models/profile");
const ClientId = process.env.CLIENTID;
const Secret = process.env.SECRET;
const Callback = process.env.CALLBACK;

//this is the empID you're getting from AHA
const empID = 7747;

//get today's date
let date_ob = new Date();

// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);

// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);

// current year
let year = date_ob.getFullYear();

// prints date in YYYY-MM-DD format
let today = year + "-" + month + "-" + date;

const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
  clientId: ClientId, //client_id
  clientSecret: Secret, //client secret
  apiVersion: "1.2" // 1.2 is the default
});

exports.getCallback = (req, res, next) => {
  const yesterday_raw = new Date(new Date().setDate(new Date().getDate() - 1));
  const yesterday = yesterday_raw.toISOString().slice(0, 10);

  client.getAccessToken(req.query.code, Callback).then(result => {
    var requests = [
      client.get("/profile.json", result.access_token), //0
      client.get("/activities/date/today.json", result.access_token), //1
      //client.get("/sleep/date/" + yesterday + ".json", result.access_token), //2
      client.get("/sleep/date/today.json", result.access_token), //2
      //client.get("/sleep/date/2019-11-05.json", result.access_token), //2
      client.get(
        "/foods/log/caloriesIn/date/today/1d.json",
        result.access_token
      ), //dailly intake of calories 3
      client.get("/foods/log/water/date/today.json", result.access_token), // 4 this works!
      client.get("/activities/heart/date/today/1d.json", result.access_token), //5
      client.get("/body/log/weight/goal.json", result.access_token, undefined, {
        "Accept-Language": "en_US"
      }), //6
      client.get("/activities/date/" + yesterday + ".json", result.access_token) //7
    ];
    Promise.all(requests)
      .then(data => {
        //profile info
        const firstName = data[0][0].user.firstName; //0
        const lastName = data[0][0].user.lastName; //0
        const dateOfBirth = data[0][0].user.dateOfBirth; //0
        const gender = data[0][0].user.gender; //0

        //calorie goals - to be burned including BMR
        const calories_goal = JSON.stringify(data[1][0]["goals"].calories); //1 calorie goal
        const massive_total = JSON.stringify(data[1][0].summary.calories.total); //1 big calorie total
        const BMR = JSON.stringify(data[1][0].summary.calories.bmr); //1 - BMR
        const calories_burned = massive_total - BMR;

        //sleep
        const slumber = JSON.stringify(
          data[2][0].summary.totalMinutesAsleep / 60
        ); //2 total sleep hours
        const sleep = JSON.stringify(Math.round(slumber * 10) / 10);

        const rem_sleep = data[2][0]["sleep"].length
          ? data[2][0]["summary"].stages.rem
          : 0; //minutes in deep REM sleep

        //nutrition
        const eating = JSON.stringify(
          data[3][0]["foods-log-caloriesIn"][0].value
        ); //3
        const caloriesIn = eating.replace(/\"/g, "");

        //water
        const water = JSON.stringify(data[4][0].summary.water);

        //heart rate
        const rhr = JSON.stringify(
          data[5][0]["activities-heart"][0].value.restingHeartRate
        );

        //body weight goal
        //res.setHeader('Accept-Language', 'en_US')
        const startWeight = JSON.stringify(data[6][0].goal.startWeight);
        const targetWeight = JSON.stringify(data[6][0].goal.weight);
        //res.send(targetWeight);

        //steps
        const totalStepsYesterday = JSON.stringify(data[7][0].summary.steps);
        const totalStepsSoFar = JSON.stringify(data[1][0].summary.steps);

        //console.log("here's where you're putting our INSERT code");

        Profile.find({ empID: empID, todaysDate: today }).then(profile => {
          if (profile) {
            //console.log("someone's here");
            profile.empID = empID;
            profile.todaysDate = today;
            profile.firstName = firstName;
            profile.lastName = lastName;
            profile.dateOfBirth = dateOfBirth;
            profile.gender = gender;
            profile.bodyStartWeight = startWeight;
            profile.bodyTargetWeight = targetWeight;
            profile.calorieGoal = calories_goal;
            profile.caloriesConsumed = caloriesIn;
            profile.caloriesBurned = calories_burned;
            profile.waterConsumpution = water;
            profile.BMR = BMR;
            profile.totalHoursSlept = sleep;
            profile.REM = rem_sleep;
            profile.RHR = rhr;
            profile.totalStepsYesterday = totalStepsYesterday;
            profile.totalStepsSoFar = totalStepsSoFar;
            return Profile.save()
              .then(result => {
                console.log("updated row");
              })
              .catch(err => {
                const error = new Error(err);
                error.httpStatusCode = 500;
                return next(error);
              });
          } else {
            const profile = new Profile({
              empID: empID,
              todaysDate: today,
              firstName: firstName,
              lastName: lastName,
              dateOfBirth: dateOfBirth,
              gender: gender,
              bodyStartWeight: startWeight,
              bodyTargetWeight: targetWeight,
              calorieGoal: calories_goal,
              caloriesConsumed: caloriesIn,
              caloriesBurned: calories_burned,
              waterConsumpution: water,
              BMR: BMR,
              totalHoursSlept: sleep,
              REM: rem_sleep,
              RHR: rhr,
              totalStepsYesterday: totalStepsYesterday,
              totalStepsSoFar: totalStepsSoFar
            });
            profile
              .save()
              .then(result => {
                console.log("got it done");
                res.redirect("/success");
              })
              .catch(err => {
                const error = new Error(err);
                error.httpStatusCode = 500;
                return next(error);
              });
          }
        });
      }) // end of update or insert
      .catch(err => {
        const error = new Error(err);
        error.httpStatusCode = 500;
        return next(error);
      });
  });
};

exports.getSuccess = (req, res, next) => {
  console.log("hello");
  res.status(200).render("authorize/success", {
    pageTitle: "Success",
    path: "/success"
  });
};

What you're looking at is good to except for the one piece of functionality that you see on line #105.

I'm trying to differentiate between adding a row or updating an already existing row.

I'm new to Node, so I'm trying to mimic the Udemy tutorial I'm going through, but I'm missing something because I keep getting an error that says, "UnhandledPromiseRejectionWarning: TypeError: Profile.save is not a function."

For the sake of brevity, that's going to be right here:

Profile.find({ empID: empID, todaysDate: today }).then(profile => {
          if (profile) {
            //console.log("someone's here");
            profile.empID = empID;
            profile.todaysDate = today;
            profile.firstName = firstName;
            profile.lastName = lastName;
            profile.dateOfBirth = dateOfBirth;
            profile.gender = gender;
            profile.bodyStartWeight = startWeight;
            profile.bodyTargetWeight = targetWeight;
            profile.calorieGoal = calories_goal;
            profile.caloriesConsumed = caloriesIn;
            profile.caloriesBurned = calories_burned;
            profile.waterConsumpution = water;
            profile.BMR = BMR;
            profile.totalHoursSlept = sleep;
            profile.REM = rem_sleep;
            profile.RHR = rhr;
            profile.totalStepsYesterday = totalStepsYesterday;
            profile.totalStepsSoFar = totalStepsSoFar;
            return Profile.save()
              .then(result => {
                console.log("updated row");
              })

That's lines 108 - 131.

What am I doing wrong?
ASKER CERTIFIED SOLUTION
leakim971
Multitechnician
Join our community to see this answer!
Unlock 1 Answer and 11 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros