Help needed with Exercise Tracker

Having trouble with the part of the test that says " You can make a GET request to api/exercise/users to get an array of all users. Each element in the array is an object containing a user’s username and _id

Here’s my code for the section:
app.get("/api/exercise/users", (req, res) => {
Per.find({}, (err, data) => {
if(!err){
res.json(data)
}
})
})

Your browser information:

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

Challenge: Exercise Tracker

Link to the challenge:

Here is a better looking version of your code, so it is easier to read.

app.get("/api/exercise/users", (req, res) => {
  Per.find({}, (err, data) => {
  if(!err){
  res.json(data)
}})
})

What error are you getting in the Chrome developer console window when you are submitting your project for testing?

Using res.json inside a callback function often leads to unexpected behaviour in my experience.

How about you try saving the result of your mongoose query to a constant variable, then sending that variable in res.json or simply using something like res.send(savedQueryResultVariable)?

Nothing shows up.

Here’s my full code:
const express = require(‘express’)
const app = express()
const cors = require(‘cors’)
require(‘dotenv’).config()
const bodyParser = require(‘body-parser’)
const mongoose = require(‘mongoose’)
const { Schema } = mongoose;

mongoose.connect(process.env.MLAB_URI ||
‘mongodb://localhost/exercise-track’, {useNewUrlParser: true}, {useUnifiedTopology: true})
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’)
});

const perSch = new Schema ({ username: {type: String, unique: true} });
const Per = mongoose.model(‘Person’, perSch);

const exSc = new Schema({userId: String, description: String, duration: Number, date: Date})
const Ex = mongoose.model(“Exercise”, exSc)

app.post(“/api/exercise/new-user”, (req, res) => {

const newPer = new Per({username: req.body.username})
newPer.save((err, data) => {
if(err){
res.json(“Username already taken”)
}else{res.json({“username”: data.username, “_id”: data.id})}
})
});

app.post(“/api/exercise/add”, (req, res) => {
const {userId, description, duration, date} = req.body;

Per.findById(userId, (err, data) => {
if(!data){
res.send(“Unknown userId”)
} else {
const username = data.username;
let newEx = new Ex({userId, description, duration, date})
newEx.save((err, data) => {
res.json({username, description, duration: +duration, _id: userId, date: new Date(date).toDateString()})
})
}

})

})

app.get(“/api/exercise/log”, (req, res) => {
const {userId, from, to, limit} = req.query;
Per.findById(userId, (err, data) => {
if(!data){
res.send(“Unknown userId”)
}else{
const username = data.username;
Ex.find({userId}, {date: {$gte: new Date(from), $lte: new Date (to)}}).select([“id”, “description”, “duration”, “date”]).limit(+limit).exec((err, data) => {
let cusdata = data.map(exer => {
let dateFormat = new Date(exer.date).toDateString();
return {id: exer.id, description: exer.description, duration: exer.duration, date: dateFormat}
})
if(!data){
res.json({
“userId”: userId,
“username”: username,
“count”: 0,
“log”:
})
}else{
res.json({
“userId”: userId,
“username”: username,
“count”: data.length,
“log”: cusdata
})
}
})
}
})
})

app.get(“/api/exercise/users”, (req, res) => {
Per.find({}, (err, data) => {
if(!err){
res.json(data)
}
})
})

app.use((req, res, next) => {
return next({status: 404, message: ‘not found’})
})

app.use((err, req, res, next) => {
let errCode, errMessage

if (err.errors){
errCode = 400
const keys = Object.keys(err.errors)
errMessage = err.errors[keys[0]].message
} else {
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)
})

Place your code inside code tags so it is easier to read please.

It looks like you did not try the thing I have recommended to you.

Let me clarify it a little bit, you are sending the response inside an if statement inside a mongoose query callback. Try to do something like:

const people = People.find({}).exec();
res.send(people );

also try console.log(people ) before the res.send to see what you are actually trying to send.

I placed that in and kept getting Promise {}.

  • Promise { <pending> }

I believe that means your query to the mongodb is not resolving the Promise.

Make sure you have properly set up the mongoose connection to your mongodb.

Welcome to the forums @duvallroberts.

To get the best advice, please post a link to your live project (like repl.it or glitch) so we can experiment.

The problem right now is that you may be mixing multiple ways of handling the asynchronous find() that you are trying to perform. Getting a Promise { <pending> } means you’ve tried to use the promises or async/await interfaces and not called a .then() or used await, and it’s really muddled because you began with a callback. To begin solving the problem, you need to decide which interface to use and then use it according to the Mongoose documentation.

If you want to use await/async (since you have the find(...).exec(), you’ll need to use await on that function call like

const people = await People.find({}).exec();

That should resolve the promise and store the found records in people, but then you will also have to make this route an async function. Then hopefully you would get something other than the unresolved promise logged to console.

You can use your call back you originally posted as well;

Just place a console.log(data); before your response and see what happens.

Good luck.

The console came back with the _id, username, _v

Well, you’ve got your data then. You should be able to build an array of JSON objects with the username and _id fields which you can then return in your response.

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