MMR
MMR

Reputation: 3029

Unable to find record by id in mongoose

I am trying to find record by id but it not getting done

var id = req.param('id');
var item = {
    '_id': id
}
videos.find(item, function(error, response) {});

I have give a valid id but still it is not fetching,can anyone suggest help,please.

Upvotes: 2

Views: 1387

Answers (2)

Saurabh Lende
Saurabh Lende

Reputation: 1013

You have to use callbacks for error handling. And find() returns array. If you need to find user by unique key (in this case _id) you must use findOne()

router.get('/GetVideoByID/:id',function(req,res){
    var id = req.params.id;
    var video = {
        '_id' : id
    }
    videos.findOne(video,function(err,data){
        if(err){
            console.log(err);
        }else{
            console.log("Video found");
            res.json(data);
        }
    });
});

Upvotes: 2

Trott
Trott

Reputation: 70125

There is a callback provided to find() but in your code above, it has no executable statements. Instead of this:

videos.find(item, function(error, response) {});

...do something like this:

videos.find(item, function(error, response) {
  if (error) {
    console.log(error); // replace with real error handling
    return;
  }
  console.log(response); // replace with real data handling
});

Upvotes: 2

Related Questions