Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:
Describe your issue in detail here.
I am having problem in completing this project.
I can’t pass test 8 and test 9
Your code so far

const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();

app.use(cors());
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));

const uri = "mongodb+srv://<username>:<password>@zikora.jqyhlcd.mongodb.net/?retryWrites=true&w=majority";
mongoose.connect(uri);

const db = mongoose.connection;

db.on("error", () => {
  console.error.bind(console, "MongoDB connection error:");
});

db.on("open", () => {
  console.log("database running successfully");
});

const Log = mongoose.model(
  "Log",
  new mongoose.Schema({
    userid: String,
    username: String,
    description: String,
    duration: Number,
    date: { type: Date, default: Date.now },
  })
);

const User = mongoose.model(
  "User",
  new mongoose.Schema({
    username: String,
  })
);

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

app.post("/api/users", async (req, res) => {
  let newUser = new User({
    username: req.body.username,
  });
  try {
    await newUser.save();
    res.json({ username: newUser.username, _id: newUser._id });
  } catch (error) {
    res.json({
      error: error.message,
    });
  }
});

app.get("/api/users", async (req, res) => {
  try {
    let allUsers = await User.find({});
    res.json(allUsers);
  } catch (error) {
    res.json({ error: error.message });
  }
});

app.post("/api/users/:id/exercises", async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      res.end("not found");
    }

    const log = new Log({
      userid: req.params.id,
      username: user.username,
      description: req.body.description,
      duration: Number(req.body.duration),
      date: req.body.date
        ? new Date(req.body.date).toDateString()
        : new Date().toDateString(),
    });

    await log.save();

    res.json({
      username: log.username,
      description: log.description,
      duration: log.duration,
      date: new Date(log.date).toDateString(),
      _id: req.params.id,
    });
  } catch (error) {
    res.json({ error: error.message });
  }
});

app.get("/api/users/:id/logs", async (req, res) => {
  const user = await User.findById(req.params.id);
  const limit = Number(req.query.limit) || 0;
  const from = req.query.from || new Date(0);
  const to = req.query.to || new Date(Date.now())

    console.log("with query");
    const log = await Log.find({
      userid: req.params.id,
      date: { $gte: from , $lte: to }
    })
    .select("-_id -userid -__v")
    .limit(limit)
    
    console.log(log)
    let userLog = log.map((each) => {
      return {
        description: each.description,
        duration: each.duration,
        date: new Date(each.date).toDateString(),
      };
    });

    res.json({
      _id: req.params.id,
      username: user.username,
      count: log.length,
      log: userLog,
    });
  
});

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 OPR/97.0.0.0

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

You should describe the precise problem and what you’ve tried, and include relevant, formatted code. It’s not that likely that someone can just browse through your code and immediately know what the issue is from that alone.

On an unrelated note you’ve published your mongo uri / password here. This is sensitive and should be stored in a .env file, and you also need to include a .gitignore and include your .env in there so it doesn’t get pushed to your repo.

You’ve included the dotenv package which is used to process those env vars and make them available to your app.

You should remove the uri from the post.

Thanks for reminding me of my mongo uri and password.

Your code is passing for me with my own DB.

Which tests are failing exactly, 8 and 9 counting from the top?

  • The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.

  • You can make a GET request to /api/users/:_id/logs to retrieve a full exercise log of any user.

Did you look in the console and network tab in the browser when submitting?

Don’t worry.
It’s passing now!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.