findById results undefined in mongoose

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

const cors = require('cors')

const mongoose = require('mongoose')
app.use(bodyParser.urlencoded({
  extended: false
}))
app.use(bodyParser.json())

mongoose.connect(process.env.MLAB_URI || 'mongodb+srv://lucifer-ux:*******@cluster0.ydagc.gcp.mongodb.net/Cluster0?retryWrites=true&w=majority', {
  useUnifiedTopology: true
}, {
  useNewUrlParser: true
}, {
  useFindAndModify: false
})
const Schema = mongoose.Schema;
app.use(cors())



app.use(express.static('public'))
app.get('/', (req, res, next) => {
  res.sendFile(__dirname + '/views/index.html')
  
});

const PersonSchema = new Schema({
  username: String,
  date: Date,
  duration: Number,
  description: String
})


const Person = mongoose.model('Person', PersonSchema);

app.post("/api/exercise/new-user", (req, res, next) => {
  const newUser = new Person({
    username: req.body.username
  })
  newUser.save(err => {
    return console.log(err)
  })
  res.json(newUser);
  next();
})

app.post("/api/exercise/add", (req, res, next) => {
  user_id = req.body.userId;
  description = req.body.description;
  duration = req.body.duration;
  req.body.date === "" ? date = new Date() :
    date = req.body.date;
  Person.findByIdAndUpdate(user_id, {
      description: description,
      duration: duration,
      date: date
    }, {
      new: true
    },
    (err, result) => {
       if (err) return console.log(err)
      res.json(result)
    })
next();
})

app.get('/api/exercise/users', (request, response, next) => {
  Person.find({}, (error, arrayOfUsers) => {
    if(!error){
      response.json(arrayOfUsers)
    }
  })
next();
})

app.get('/api/exercise/log',(req,res)=>{
  let search=req.query.userId
  console.log(search)
  Person.findById({search},(err,result)=>{
  console.log(result)    
  })
})



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

This is the entire code so far I was doing API projects

app.get('/api/exercise/log',(req,res)=>{
  let search=req.query.userId
  console.log(search)
  Person.findById({search},(err,result)=>{
  console.log(result)    
  })
})

this part of the code is supposed to perform a query but result part of the findById function returns undefined I dont know why please help

Hello there,

You likely need to convert the id into an ObjectId. This is done through the mongodb package:

const ObjectId = require('mongodb').ObjectId;

const myIdObject = ObjectId(theIdToConvert);
// Now you can use myIdObject
// as a search parameter within a Mongo method

Hope this helps

It still says undefined I did something like this

const ObjectId = require(‘mongodb’).ObjectId;
this is where I required my packages

app.get(’/api/exercise/log’,(req,res)=>{
const myIdObject = ObjectId(req.query.userId);
console.log(myIdObject)
Person.findById({myIdObject},(err,result)=>{
console.log(result)
})
})
and this at the get part…
Am I doing something wrong??? :sweat_smile:

This is how I did it in my app:

myDataBase.find({_id: new ObjectId(req.query.userId)})

My earlier comment was missing the new keyword.

Now it actually is not returning anything the Get request just keeps on loading
Person.find({_id: new ObjectId(req.query.userId)},(err,result)=>{
console.log(result)
res.json(result)
})

this is how we return the result right ?? :sweat_smile: :sweat_smile:

Ag, I am sorry about that; my implementation does not use Mongoose :man_facepalming:

For Mongoose, I do not think the ObjectId is necessary.

Would you mind sharing a CodeSandbox/Repl.it (or similar) of your project? Even a GitHub repo that I could clone would do. It would make it easier to debug.

Yes of course I haven’t yet uploaded the code to github I will send the link here ASAP but now even the POST request to add description and all also broke down I think my code is very very wrong :sweat_smile: :sweat_smile:

https://github.com/lucifer-ux/FCC This is the repository. Thank you so much @Sky020

1 Like

I am unable to use your repo within any browser, because you have included the node_modules folder. This makes the repo size too large.

It is not good practice to include it within a repo. For future projects, I suggest you use a .gitignore file, and be sure to include both node_modules, and .env in it.

Would you mind deleting the node_modules folder from the repo?

1 Like

oops my bad i forgot about gitignore :sweat_smile: :sweat_smile: :sweat_smile: sorry I will fix it right now

https://github.com/lucifer-ux/FCC I corrected it sorry for the trouble @Sky020

Thanks for that.

Some notes:

  1. I had to install dotenv as a dependency.
  2. name is not initialised:
name = req.body.username;
  1. mongoose.connect should only have 2 arguments. Yours currently has 4:
  • 1: The connection string
  • 2: The options (Options are one, single object with multiple properties)
  1. I had to update mongodb and mongoose
  2. It is odd that you are trying to create, save, and then immediately find a user:
newUser.save();

  const new_user = Person.findOne({ username: name }, (err, docs) => {
    console.log(docs);
  });
  • Just create, save, then return the saved document (or, an error message, saying the document could not be saved)
  • These operations are asynchronous. So, you cannot save, and immediately find the same document.
  1. Do not focus on the /api/exercise/log route, until you can reliably create and save a user (/api/exercise/new-user)

I hope this helps.

Actually it was working I saved a lot of data by using it I aimed at creating a Schema and then saving only the username to it initially and then use the _id that user submits to find the same collection and update it with the rest of the data and then display it . It was working initially but then I played around too much with the code when log was not working and messed up :sweat_smile: :sweat_smile: :sweat_smile:
This helps big time as I forgot about /new-user and got too involved in log :sweat_smile: :sweat_smile: Stupid me
THANK YOU SO MUCH