node.jsmongodbexpressglitch-framework

nodejs application is works fine in local gives error in glitch.com


am doing APIs and Microservices Projects - Exercise Tracker project in freecodecamp

i have build a mini project which is working fine in my local so i have hosted it in glitch.com

in that am facing some error project link please help me to solve this

server.js

const express = require("express");
const app = express();
const bodyParser = require("body-parser");

const cors = require("cors");
const { newUser, addExercise, showLogs } = require("./api/index.js");

const mongoose = require("mongoose");

mongoose.connect(process.env.MLAB_URI || "mongodb://localhost/exercise-track");

app.use(cors());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static("public"));
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/views/index.html");
});

app.post("/exercise/new-user", (req, res) => newUser(req, res));
app.post("/exercise/add", (req, res) => addExercise(req, res));
app.get("/exercise/log", (req, res) => showLogs(req, res));

// Not found middleware
app.use((req, res, next) => {
  return next({ status: 404, message: "not found" });
});

// Error Handling middleware
app.use((err, req, res, next) => {
  let errCode, errMessage;

  if (err.errors) {
    // mongoose validation error
    errCode = 400; // bad request
    const keys = Object.keys(err.errors);
    // report the first validation error
    errMessage = err.errors[keys[0]].message;
  } else {
    // generic or custom error
    errCode = err.status || 500;
    errMessage = err.message || "Internal Server Error";
  }
  res
    .status(errCode)
    .type("txt")
    .send(errMessage);
});

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

and index.js file is here

const User = require ('../model/user.js');
const Exercise = require ('../model/exercise.js');
const moment = require ('moment');

exports.newUser = function(req, res) {
  let name = req.body.username;
  if (!name) name = 'Mr/Mrs Doe';

  User.findOne({ name: name })
    .then( (user) => {
      if (user) return new Promise( (resolve,reject) => reject('User already exists') );
      else return new User({ name }).save();
    })
    .then( (newUser) => {
      if(!newUser.isNew) res.json({ userId: newUser.userId, name: newUser.name });
    })
    .catch( (error) => res.status(422).json({ error }) );
};


exports.addExercise = function(req, res) {
  // Dates are coming in in this format = 'YYYY-MM-DD';
  let { userId, description, duration, date } = req.body;
  console.log('description:', description, ' - duration: ', duration, ' - date: ', date);
  if (!description) description = 'No description provided';
  if (!duration) duration = '0';
  if (!date) date = moment();

  User.findOne({ userId })
    .then( (user) => {
      if (user) {
        // console.log('---1. Date: ', date);
        const exercise = new Exercise({ description, duration, date });
        exercise.userId.push(user);
        user.exercises.push(exercise);
        return Promise.all([exercise.save(), user.save()]);
      }
      else return new Promise( (resolve,reject) => reject('UserId not found') );
    })
    .then( (exercise) => {
      if(!exercise.isNew) res.json({ userId, description, duration, date: moment(date).format('D MMM, YYYY') });
      else return new Promise( (resolve,reject) => reject('Exercise could not be saved') );
    })
    .catch( (error) => res.status(422).json({ error }) );
};


exports.showLogs = function(req, res) {
  const { userIdLogs, fromDate, toDate } = req.query;
  var populateExercises = (from, to) => {
    let params = {
      path: 'exercises',
      // match: { date : populateExercises(fromDate, toDate) },
      select: 'description duration date',
      options: { sort: { date: -1 }}
    };

    if(from && to) params.match = { date : { $gte: from, $lte: to } };
    else if (from) params.match = { date : { $gte: from } };
    else if (to) params.match = { date : { $lte: to } };
    return params;
  };

  // see if the userId exists
  User.findOne({ userId: userIdLogs })
    .populate( populateExercises(fromDate, toDate) )
    .then( (user) => {
      if (!user) return new Promise( (resolve,reject) => reject('UserId not found') );
      else {
        const { userId, name } = user;
        res.json({
          search: { userId, name, fromDate, toDate },
          total: user.total,
          exercises: user.exercises.map(function(exercise){
            // exercise.bla = moment(exercise.date).format('D MMM, YYYY');
            return {
              _id: exercise._id,
              description: exercise.description,
              duration: exercise.duration,
              date: moment(exercise.date).format('D MMM, YYYY')
            };
          })
        });
      }
    })
    .catch( (error) => res.status(422).json({ error }));
};

error log is here

module.js:478
    throw err;
    ^
Error: Cannot find module '../model/exercise.js'
    at Function.Module._resolveFilename (module.js:476:15)
    at Function.Module._load (module.js:424:25)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/api/index.js:2:18)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/server.js:6:44)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
module.js:478
    throw err;
    ^
Error: Cannot find module '../model/exercise.js'
    at Function.Module._resolveFilename (module.js:476:15)
    at Function.Module._load (module.js:424:25)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/api/index.js:2:18)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/server.js:6:44)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)

but in my local it works fine and i can run my project


Solution

  • Good day, it appears that your file name is execise.js but you are trying to import exercise in /api/index.js. Please edit the file name of mode/execise.js to be exercise.js