Trying to render a template based on result from mongoose schema's findOne() method

I'm trying to use a task id generated in mongoDB to render a template which takes the task id as an input. I'm new to node and mongoDB so I apologize for any wrong terminologies. The findOne method below returns null for the data parameter in its callback function though the task id is populated in the url.

I have tried using exec() and chaining then() but the implementation does not result in data being populated. Also, the MongoDB version is 3.4.

var express = require('express');
var router = express.Router();

router.get('/createTask', function(req, res) {
  var newTask = new Task();

  newTask.save(function( err, data) {
    if (err) {
      console.log(err);
      res.render('error');
    } else {
      res.redirect('/task/' + data._id);
    }
  })
});

router.get('/task/:id', function(req, res) {
  if (req.params.id) {
    Task.findOne({_id: req.params.id}, function(err, data) {
      if (err) {
        console.log(err);
        res.render('error');
      }

      if (data) {
        res.render('task', {data: data});
      } else {
        res.render('error');
      }
    })
  } else {
    res.render('error');
  }
});

module.exports = router;

This should render the task template with a simple h1 added to test but instead returns a blank page.

1 answer

  • answered 2019-04-15 06:21 PrivateOmega

    My guess is _id is an ObjectID type field, which means you cannot do task.findOne({ _id: req.params.id }) and get the document in the data argument of callback function.

    Instead use the oId variable instead of req.params.id in task.findOne()

    const mongo = require('mongodb');
    const oId = new mongo.ObjectID(req.params.id);