1

When I am using req.body.post in Post.findById it gives undefined but when I use direct id in Post.findById it workes fine. Console.log(req.body.post) give correct id but using it in Post.findById gives undefined why undefined while console.log give correct id

const Post = require('../models/post');

module.exports.create = function(req,res){
    console.log(req.body.post);
    Post.findById(req.body.post,function(err,post){
        console.log(post);
        return res.redirect('/');
    })
}
Output
62175534d37c9ce165033cee 
undefined

when I use direct id which is console.log print then it works fine.

const Post = require('../models/post');

module.exports.create = function(req,res){
    console.log(req.body.post);
    Post.findById('62175534d37c9ce165033cee',function(err,post){
        console.log(post);
        return res.redirect('/');
    })
}
Output
{
  comment: [],
  _id: new ObjectId("62175534d37c9ce165033cee"),        
  content: 'sdf',
  user: new ObjectId("621749248e7de90faa6263d4"),       
  createdAt: 2022-02-24T09:51:48.621Z,
  updatedAt: 2022-02-24T09:51:48.621Z,
  __v: 0
}
Phil
  • 157,677
  • 23
  • 242
  • 245
vishal singh
  • 41
  • 1
  • 5

2 Answers2

0

console.log() output can sometimes be misleading, if you log an object expression. It may print a value that was not yet set at the time, when the code execution reached the console.log() statement (look here, for example: console.log() async or sync?)

To be on the safe side with your logging output, modify your code like this:

const Post = require('../models/post');

module.exports.create = function(req,res){
    const stringToLog = req.body.post;
    console.log(stringToLog);
    Post.findById(req.body.post,function(err,post){
        console.log(post);
        return res.redirect('/');
    })
}

Don't be surprised if this leads to a different result (or maybe it doesn't).

Mario Varchmin
  • 3,704
  • 4
  • 18
  • 33
-1

You need to import ObjectId from mongodb. Than you try to find id like next:

db.colection_name.find(ObjectId('621749248e7de90faa6263d4'))

As you see in your database, it's not just a simple string, it's an object.

ref: https://docs.mongodb.com/manual/reference/method/ObjectId/