Sunday, 11 June 2017

Mongoose Schema in NodeJS TypeError: Schema is not a constructor

I'm trying to build a MEAN Stack application for university and I'm pretty new to that stuff. I did a tutorial on how to implement login and registration. Currently, npm start tells me that New Schema ist not a constructor. I've already looked for an answer but couldn't really finde one. So heres my code:

    // imported libraries---------------------
    var mongoose = require('mongoose');
    var Schema = mongoose.schema;
    var crypto = require('crypto');
    var jwt = require('jsonwebtoken'); //generates our token which is required for 
    logging in

    //Mongoose userScheme --------------------
    var userSchema = new Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    //@arg hash: hashes provide security if the db is hacked --> password is 
    hashed
    hash: String,
    salt: String
    });
    /*
    The following setPassword method takes the password and salt to create
   a safe password and a salt which is then synchronized with the the DB
   This method runs with every user login / registration
   */
    userSchema.methods.setPassword = function(password){
    this.salt = crypto.randomBytes(16).toString('hex');
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');

    };
    // checks if the entered password matches with the password stored in DB (hashed)
   //returns a boolean
   userSchema.methods.validPassword = function(password){
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
    return this.hash === hash;
    };

    userSchema.methods.generateJwt = function(){
    var expiry = new Date();
    expiry.setDate(expiry.getDate()+7); //token expires seven days after creation

    return jwt.sign({
        _id: this._id,
        email: this.email,
        name: this.name,
        exp : parseInt(expiry.getTime()/1000),

        }, "MY_SECRET"); //todo add this secret to mongo db
    };

An here is the error message:

TypeError: Schema is not a constructor
at Object.<anonymous> 

(/Users/Dominik/IDE/ideaProjects/groupup/SEBA_GroupUp/app_api/models/users.js:13:18)

I also checked the documentation for mongoose but I to me the type things didn't look bad. Thank you in advance for your help!



via dominikger

No comments:

Post a Comment