Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:
I’m passing all tests but one:

“Each element in the array returned from GET /api/users is an object literal containing a user’s username and _id .”

When I look at the output data I notice that instead of returning :

{
  username: "fcc_test",
  _id: "5fb5853f734231456ccb3b05"
}

It returns :

{
  _id: new ObjectId("63375e39b845bbbefc098532"),
  username: 'fcc_test_16645729857',
}

Could this be the problem?

Your code so far

const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()

var bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});


const Schema = mongoose.Schema;
const userSchema = new Schema({
  username: {
    type: String,
    required: true},
  count: Number,
  log: [{
    description: String,
    duration: Number,
    date: {type: String, required: false},
    _id: false
  }]
});

const User = mongoose.model("User", userSchema);

app.post("/api/users", (req, res) => {
  const username = req.body.username;

  const user = new User({
    username: req.body.username
  });

  User.findOne({ username: username }, (err, foundUser) => {
    if (err) {
      console.log(err);
    }

    if (!foundUser) {
      user.save((err, user) => {
        if (err) {
          console.log(err);
        }
        console.log(`user ${user.username} saved to database!`);
      });
    }

    res.json({
      username: user.username,
      _id: user._id
    });
  });
});

app.get("/api/users", (req, res) => {
  User.find({}, (err, foundUsers) => {
    if (err) {
      console.log(err);
      res.json({ error: err });
    }

    if (foundUsers.length === 0) {
      res.json({ error: "No users in database" });
    }

    res.json(foundUsers.map(user => {
      const { __v, ...rest } = user._doc;
      console.log(rest);
      return rest;
    }));
  });
});```

**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36</code>

**Challenge:**  Back End Development and APIs Projects - Exercise Tracker

**Link to the challenge:**
https://www.freecodecamp.org/learn/back-end-development-and-apis/back-end-development-and-apis-projects/exercise-tracker

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