TypeError: Cannot read property 'title' of null

I am getting this JavaScript error:

TypeError: Cannot read property 'title' of null

Here is the code:

Mds-iMac:cmscart imac$ nodemon app [nodemon] 1.11.0 [nodemon] to restart at any time, enter rs [nodemon] watching: . [nodemon] starting node app app.js (node:2274) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection(). See http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client (node:2274) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html Server started on port 3200 Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials. Connected to MongoDB

events.js:182
  throw er; // Unhandled 'error' event
  ^

TypeError: Cannot read property 'title' of null

at /Users/imac/Desktop/cmscart/routes/pages.js:17:24
at model.Query.<anonymous> (/Users/imac/Desktop/cmscart/node_modules/mongoose/lib/model.js:4074:16)
at /Users/imac/Desktop/cmscart/node_modules/kareem/index.js:273:21
at /Users/imac/Desktop/cmscart/node_modules/kareem/index.js:131:16
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)

[nodemon] app crashed - waiting for file changes before starting...

The page.js code is:

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

// Get Page model
var Page = require('../models/page');

/*
 * GET /
 */
router.get('/', function (req, res) {

Page.findOne({slug: 'home'}, function (err, page) {
    if (err)
        console.log(err);

    res.render('index', {
        title: page.title,
        content: page.content
    });
});

});

/*
 * GET a page
 */
router.get('/:slug', function (req, res) {

var slug = req.params.slug;

Page.findOne({slug: slug}, function (err, page) {
    if (err)
        console.log(err);

    if (!page) {
        res.redirect('/');
    } else {
        res.render('index', {
            title: page.title,
            content: page.content
        });
    }
});


});

// Exports
module.exports = router; 

The error is occuring inside the JavaScript functions at title: page.title, above.

Please help me out.

Upvotes: 1

Views: 7794

Answers (3)

Amandeep Saini
Amandeep Saini

Reputation: 928

router.get('/edit-page/:slug', (req, res) => {
  Page.findOne({slug : req.params.slug}).then((page) => {
    if(!page) { //if page not exist in db
      return res.status(404).send('Page not found');
    }
    res.render('admin/edit_page', { //page  exist
      title: page.title,
      slug: page.slug,
      content: page.content,
      id: page._id
    });
  }).catch((e) => {//bad request 
    res.status(400).send(e);
  });
});

Use this code it will work the logic is same but i have handled the conditions using promises it definitely worked for me. Hope it helps you :)

Upvotes: 2

generalhenry
generalhenry

Reputation: 17319

if (err)
   console.log(err);

Is one issue. When you get an error you should return an http error then exit the function eg:

if (err) {
    console.log(err);
    res.statusCode = 500;
    res.end('error');
}

When there is an error the page variable will be null, which explains the exception thrown.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370829

It means that when

function (err, page) {

was called, inside of Page.findOne, the page argument did not have a property of title.

(without context of how Page.findOne is being used, hard to say how to fix it)

Upvotes: 0

Related Questions