Cannot read property 'findOne' of undefined in Node and Sequelize

Issue

This is my admin_pages.js file i have done the migrations and models but i am getting this error.

TypeError: Cannot read property ‘findOne’ of undefined
at C:\users\gaffer\desktop\gaffercart\routes\admin_pages.js:80:21
at Layer.handle [as handle_request] (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\layer.js:95:5)
at next (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\layer.js:95:5)
at C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:335:12)
at next (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:174:3)
at router (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:317:13)
at C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:335:12)
at next (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:275:10)
at C:\users\gaffer\desktop\gaffercart\index.js:70:3
at Layer.handle [as handle_request] (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:317:13)
at C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:335:12)
at next (C:\users\gaffer\desktop\gaffercart\node_modules\express\lib\router\index.js:275:10)
at C:\users\gaffer\desktop\gaffercart\node_modules\connect-flash\lib\flash.js:21:5

var express=require('express');
var router=express.Router();
var expressValidator = require('express-validator');
var bodyParser=require('body-parser');
var models=require('../models');

// var mysql=require('mysql');
// var Sequelize=require('sequelize');
// var DataTypes=Sequelize.DataTypes;
// var sequelize = exports.sequelize = module.parent.exports.sequelize;
// let sequelize=new Sequelize();

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

/*
* GET PAGES INDEX its correct but commiting it
*/

 router.get('/',function(req,res){
 //  Page.find({}).sort({sorting: 1}).exec(function(err,pages){
    res.render('admin/pages',{ 
      //pages:pages
    });
   });
 //});
//  router.get('/admin/dashboard',function(req,res){
//    res.render('admin/dashboard');
//  });


/*
** GET ADD PAGE
*/
 router.get('/add-page',function(req,res){
   var title="";
   var slug="";
   var content="";


   res.render('admin/add_page',{
      title:title,
      slug:slug,
      content:content

   });

 });

//POST ADD page
 router.post('/add-page',function(req,res){
  //  console.log("alsdjlajsi")

  req.checkBody('title','Title must have a body.').notEmpty();
  req.checkBody('content','Content must have a body.').notEmpty();

  var title = req.body.title;
  var slug = req.body.slug.replace(/\s+/g, '-').toLowerCase();
  if(slug == " ")  
  {
    slug = title.replace(/\s+/g, '-').toLowerCase();
  }
  var content = req.body.content;
  var errors = req.validationErrors();

  //If there are Errors then define it on the same page
  if(errors){
    res.render('admin/add_page',{
      errors:errors,
      title:title,
      slug:slug,
      content:content
    });
  }
  /*
  * Have use Pages
  */
      else{

        models.Page.findOne({slug:slug}, function(err, page){

        if(page){
          req.flash('danger','Page slug Already Exist,');
          res.render('admin/add_page',{

            title:title,
            slug:slug,
            content:content
          });
        }
        else{
            var page = new Page({
              title:title,
              slug:slug,
              content:content,
              sorting:100
            });
            page.save(function(err){
              if(err) return console.log(err);

              req.flash('success','Page Added Successfully!!');
              res.redirect('/admin/pages');
            });
        }
      });

  }

});
//Exports
module.exports=router;

This is mine Page models

'use strict';
// var Sequelize=require('sequelize');

module.exports = (sequelize, DataTypes) => {
  var page = sequelize.define('page', {
    title: DataTypes.STRING,
    slug: DataTypes.STRING,
    content: DataTypes.STRING,
    sorting:DataTypes.INTEGER
  }, {});
  page.associate = function(models) {
    // associations can be defined here
  };
  return page;
};

Solution

You’ve defined your Page model as 'page' (lowercase):

var page = sequelize.define('page', {...})

But are using it as:

 models.Page.findOne(...) // uppercase

Either use models.page or change your model definition to be uppercase:

var page = sequelize.define('Page', {...}) // uppercase

Also change this:

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

to this:

const Page = require('../models').Page // or .page if you keep your definition lowercase

findOne does not take a function callback, and you must use where to search by the slug property. Use the following:

else { 
  models.Page.findOne({ 
    where: { slug }  // destructuring
  })
  .then((page) => {
    // work with the page instance
  })
  .catch((err) => {
    // error case
  })

}

same with page.save():

page.save()
  .then(() => {
    req.flash('success','Page Added Successfully!!');
    res.redirect('/admin/pages');
  })
  .catch((err) => {
    // handle error
  })

Answered By – vapurrmaid

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published