Error Message: Cannot read property of undefined - MongoDb, nodejs

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tdrsam
    New Member
    • May 2015
    • 97

    Error Message: Cannot read property of undefined - MongoDb, nodejs

    I'm trying to add a MongoDb database to a nodejs app. I've never done this before and don't know how it works. I seem to have the Db installed, but I don't seem to be able to send data to it from a web form.

    I have this in my app.js file:

    Code:
    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/emedb');
    var app = express();
    
    var Schema = mongoose.Schema;
    
    // create a schema
    var userSchema = new Schema({
      moniker: { type: String, required: true,},
      email: { type: String, required: true,},
      password: { type: String, required: true },
      location: String,
      age: Number,
      created_at: Date,
      updated_at: Date
    });
    
    // on every save, add the date
    userSchema.pre('save', function(next) {
      // get the current date
      var currentDate = new Date();
      
      // change the updated_at field to current date
      this.updated_at = currentDate;
    
      // if created_at doesn't exist, add to that field
      if (!this.created_at)
        this.created_at = currentDate;
    	
      next();
    });
    
    var User = mongoose.model('emedb', userSchema);
    
    // post to db
    app.post('/newBen', function(req, res){
    	new User({
    		moniker: req.body.moniker,
    		email: req.body.email, 
    		password: req.body.password,
    		location: req.body.location,
    		age: req.body.age,
    		created_at: req.currentDate,
    		updated_at: req.currentDate
    	}).save(function(err, doc){
    		if(err)res.json(err);
    		else res.send('Thank you for joining');
    	});res.end();
    });
    
    module.exports = User;
    
    
    /*
    app.use(function(req,res,next){
        req.db = emedb;
        next();
    });
    */
    
    var routes = require('./routes/index');
    var users = require('./routes/users');
    And this is my jade file with the form that the data is supposed to be sent from:

    Code:
    extends layout
    
    block content
      form(name='regBenForm' class='regForm' action='/newBen' method='post')
        label(for='moniker') Name
        input(type="text", name="moniker", id="moniker")
        label(for='email') Email
        input(type="email", name="email")
        label(for='password') Password
        input(type="password", name="password")
        label(for='passwordMatch') Repeat Password
        input(type="password", name="passwordMatch")
        label(for='age') Age
        input(type="number", name="age")
        label(for='location') Location
        input(type="text", name="location")
        button(type="submit" class='submitBtn') Go
    And this is the error message I get in the broswer:

    Code:
    TypeError: Cannot read property 'moniker' of undefined
        at D:\node\eme\app.js:47:20
        at Layer.handle [as handle_request] (D:\node\eme\node_modules\express\lib\router\layer.js:95:5)
        at next (D:\node\eme\node_modules\express\lib\router\route.js:131:13)
        at Route.dispatch (D:\node\eme\node_modules\express\lib\router\route.js:112:3)
        at Layer.handle [as handle_request] (D:\node\eme\node_modules\express\lib\router\layer.js:95:5)
        at D:\node\eme\node_modules\express\lib\router\index.js:277:22
        at Function.process_params (D:\node\eme\node_modules\express\lib\router\index.js:330:12)
        at next (D:\node\eme\node_modules\express\lib\router\index.js:271:10)
        at expressInit (D:\node\eme\node_modules\express\lib\middleware\init.js:33:5)
        at Layer.handle [as handle_request] (D:\node\eme\node_modules\express\lib\router\layer.js:95:5)
        at trim_prefix (D:\node\eme\node_modules\express\lib\router\index.js:312:13)
        at D:\node\eme\node_modules\express\lib\router\index.js:280:7
        at Function.process_params (D:\node\eme\node_modules\express\lib\router\index.js:330:12)
        at next (D:\node\eme\node_modules\express\lib\router\index.js:271:10)
        at query (D:\node\eme\node_modules\express\lib\middleware\query.js:49:5)
        at Layer.handle [as handle_request] (D:\node\eme\node_modules\express\lib\router\layer.js:95:5)
    I'm not sure if it's to do with the code I've commented out in the app.js file - around line 60 - or I just haven't properly called the form input.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    from the message it looks req.body does not exist. I don’t know which version of express you’re using, so I can only point out its documentation.

    Comment

    • tdrsam
      New Member
      • May 2015
      • 97

      #3
      That seems correct. I removed .body from all of the items to be posted to the db. Now, when I run a test in the browser, it redirects to the action of the form, which is /newBen. Another quick question. Do I use that file to post the data to the db, or can I use it to redirect to a new page, or both?

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        what file?

        Comment

        • tdrsam
          New Member
          • May 2015
          • 97

          #5
          The /newBen file. I could use that a redirect. But it looks like the data I sent from the browser wasn't inserted to the db. I don't suppose you know of any MongoDB tutorials that would explain it?

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            The /newBen file.
            there is no such file. /newBen is a route in your application that is handled by the function defined in Express.

            I don't suppose you know of any MongoDB tutorials that would explain it?
            I think you would need an Express tutorial, rather than a mongoose tutorial (a MongoDB tutorial won’t help as you don’t interact directly with MongoDB as would be the case if you’d use the MongoDB client on the command line)

            Comment

            • tdrsam
              New Member
              • May 2015
              • 97

              #7
              Ok. Will look for that. Thanks for the help.

              Comment

              • mqasimkhan
                New Member
                • Sep 2021
                • 1

                #8
                you have any solution of this ERROR in node.js, express.js, mongoose

                {"errors":{"ema il":{"name":"Va lidatorError"," message":"Canno t read property 'isEmail' of undefined","pro perties":{"mess age":"Cannot read property 'isEmail' of undefined","typ e":"user defined","path" :"email","value ":"qasim.soften g29@gmail.com", "reason":{}},"k ind":"user defined","path" :"email","value ":"qasim.soften g29@gmail.com", "reason":{}},"a ddress":{"name" :"ValidatorErro r","message":"P ath `address` (`Bannu`) is shorter than the minimum allowed length (10).","propert ies":{"message" :"Path `address` (`Bannu`) is shorter than the minimum allowed length (10).","type":" minlength","min length":10,"pat h":"address","v alue":"Bannu"}, "kind":"minleng th","path":"add ress","value":" Bannu"},"addres s2":{"name":"Va lidatorError"," message":"Path `address2` (`New York`) is shorter than the minimum allowed length (10).","propert ies":{"message" :"Path `address2` (`New York`) is shorter than the minimum allowed length (10).","type":" minlength","min length":10,"pat h":"address2"," value":"New York"},"kind":" minlength","pat h":"address2"," value":"New York"}},"_messa ge":"User validation failed","name": "ValidationErro r","message":"U ser validation failed: email: Cannot read property 'isEmail' of undefined, address: Path `address` (`Bannu`) is shorter than the minimum allowed length (10)., address2: Path `address2` (`New York`) is shorter than the minimum allowed length (10)."}

                Comment

                Working...