Accessing Data from find method

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);
});

I think we would need to be able to see your code in order to give you good help.

When you log out data inside the callback what exactly do you get back and are you sure you are reading the structure correctly. It seems unlikely that you can see the property on data when logging it out but not get to it.

BTW, you are asking about findById but you are using find.

I was messing with the program and now data is just “” when I print it to the console. So, now I have no idea what could be wrong.

But also the findById mention was a mistake, I meant to just say find.

It has to be matching with the correct “._id” though because it does output saying “unknown userid”. So I don’t understand why data would appear empty when I try to print it or access things that should be inside of it

I actually solved the problem, I used findById instead of find, and I was able to get the information from data that way. Not sure why there is a difference but it worked.