Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validation Error in mongoose and node.js (ERROR IS BELOW)

I am getting this error

this.$__.validationError = new ValidationError(this);

The full error message will be below the codes

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index.js file

//Requiring Dependencies
const express = require('express');
const app = express();

const mongoose = require('mongoose');

const path = require('path');

const session = require('express-session');

const passport = require('passport');
const LocalStrategy = require('passport-local')

//Require Models
const Product = require('./models/product');
const User = require('./models/user');

//To run and parse EJS
const engine = require('ejs-mate');

//Connecting to DB server
mongoose.connect('mongodb://localhost:27017/ecom', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
    .then(() => {
        console.log('DATABASE CONNECTED')
    })
    .catch(err => {
        console.log('SOMETHING WENT WRONG WITH MONGO')
        console.log(err)
    })

    //Using EJS-Mate
    app.engine('ejs' , engine);
    app.set('view engine' , 'ejs');
    app.set('views' , path.join(__dirname, 'views'));

    const sessionConfig = {
        secret: 'secrethere',
        resave: false,
        saveUninitialized: true,
        cookie: {
            httpOnly: true,
            expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
            maxAge: 1000 * 60 * 60 * 24 * 7
        }
    }
    app.use(session(sessionConfig))

    //Using Passport
    app.use(passport.initialize())
    //So user does not have to login after every single request
    app.use(passport.session())
    passport.use(new LocalStrategy(User.authenticate()))

    
    //How to store a user in the session
    passport.serializeUser(User.serializeUser());

    //How to get user out of that session
    passport.deserializeUser(User.deserializeUser());


    app.use(express.urlencoded({extended: true}));

    //For use of files like js and css in public directory
    app.use(express.static(path.join(__dirname, './public')))

    app.use(express.static(path.join(__dirname, './images')))

   


    app.get('/' , (req , res) => {

    })

    app.get('/home' , (req , res) => {
        res.render('pages/homepage')
    })

    app.get('/login' , (req , res) => {
        res.render('pages/loginPage')
    })

    app.get('/signup' ,(req , res) => {
        res.render('pages/signup')
    })

    //Creating a new user
    app.post('/signup' , async(req , res) => {
        const {username , email, password, country, city, zipcode, street} = req.body
        const user =  new User({
            username,
            email,
            country,
            city,
            zipcode,
            street
        })
      const registeredUser = await User.register(user, password);
      console.log(registeredUser)
    })


    //Port
app.listen(3000, () => {
    console.log('LISTENING ON PORT 3000')
})

This is the user model file

const express = require('express')
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');

const userSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    username: {
        type: String,
        required: true
    },
    address: {
        country: {
            type: String,
            required: true
        },
        city:{
            type: String,
            required: true
        },
        street: {
            type: String,
            required: true
        },
        zipcode: {
            type: String,
            required: true
        }
    },
    shipping_address: {
        country: {
            type: String,
            required: true
        },
        street: {
            type: String,
            required: true
        },
        zipcode: {
            type: String,
            required: true
        }
    }
});
//Using Paspport Plugin
userSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('User' , userSchema);

This is the full error

C:\Users\hadiz\Desktop\Business\portfolioprojects\ecommerce\node_modules\mongoose\lib\document.js:2907
this.$__.validationError = new ValidationError(this);
^

ValidationError: User validation failed: shipping_address.zipcode:
Path shipping_address.zipcode is required., shipping_address.street:
Path shipping_address.street is required., shipping_address.country:
Path shipping_address.country is required., address.zipcode: Path
address.zipcode is required., address.street: Path address.street
is required., address.city: Path address.city is required.,
address.country: Path address.country is required.
at model.Document.invalidate

>Solution :

You should refer to the nested properties of the address and shipping_address objects in your schema when registering a new user:

app.post('/signup', async (req, res) => {
  const { username, email, password, country, city, zipcode, street } =
    req.body;
  const user = new User({
    username,
    email,
    address: { country, city, zipcode, street },
    shipping_address: { country, city, zipcode },
  });
  const registeredUser = await User.register(user, password);
  console.log(registeredUser);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading