I’m currently working on the Exercise Tracker Project from the API and Microservices chapter.
When using
user.find({"_id":userId}, (err,data) =>
I want to be able to access the username that is in the data found.
However, “data.username” keeps coming back as “undefined”. but I know there is a data because I can print it to the console and visibly see the username.
Does anyone have any clue why this is happening?
here is my code, the problem is occuring in the
“app.post(”/api/users/:_id/exercises","
//All requirements
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const multer = require("multer");
const upload = multer();
const cors = require("cors");
const mongoose = require("mongoose");
const Schema = mongoose.Schema
//Connect to DB
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
// useUnifiedTopology: true,
useCreateIndex: true
});
//Use the requirements
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// // let's make json a bit cleaner
//Send the HTML
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
const personSchema = new Schema({ username: String})
const user = mongoose.model('user', personSchema)
const exerciseSchema = new Schema(
{
userId: Number,
description: String,
duration: Number,
date: Date
})
const exercise = mongoose.model('exercise', exerciseSchema)
app.post("/api/users", (req,res)=>{
const newPerson = new user({username:req.body.username});
newPerson.save((err,data)=>{
res.json({username: data.username, "_id": data._id})
console.log(data.username)
})
});
app.post("/api/users/:_id/exercises", (req,res) =>{
const {userId, description, duration, date} = req.body;
user.find({"_id":userId}, (err,data) =>{
if(!data){
res.send("Unknown userId")
}else{
const newExercise = new exercise({userId, description, duration, date});
newExercise.save((err,data)=>{
res.json({userId, description, duration, date})
})
}
})
})
// 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);
});