Saturday, 15 April 2017

Mongoose error in required properties

I'm connecting a Angular 2 app to MongoDB via Mongoose. I'm trying to store some data, but i obtain an error on all required properties.

I set up a schema, serverside:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var uniqueValidator = require("mongoose-unique-validator");

var schema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    nome: {
        type: String,
        required: true
    },
    cognome: {
        type: String,
        required: true
    },
    dataNascita: {
        type: Date
    },
    telefono: {
        type: String
    },
    classifica: {
        type: String
    }
});

schema.plugin(uniqueValidator);

module.exports = mongoose.model("User", schema);

The user object is clearly filled:

User Object

Mongoose responds with an error:

Error Object

Thanks in advance for any help. Max

Update:

The call from a Angular service:

@Injectable()
export class AuthService {

    constructor(private http: Http) {

    }

    addUser(utente: Utente) {
        const body = JSON.stringify(utente);
        return this.http.post('http://localhost:3000/utente', body)
            .map((response: any) => {
                console.log(response);
                response.json();
            })
            .catch((error: Response) => Observable.throw(error.json()
            ));
    }
}

The Moongose call:

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

var User = require('../models/users');

router.post('/', function (req, res, next) {
    var user = new User({
        email: req.body.email,
        password: req.body.password,
        nome: req.body.nome,
        cognome: req.body.cognome,
        dataNascita: req.body.dataNascita,
        telefono: req.body.telefono,
        classifica: req.body.classifica
    });
console.log(res);
    user.save(function (err, result){
        console.log(err);
        console.log(res);
        if (err){
            return res.status(500).json({
                titolo: "Errore durante il salvataggio",
                errore: err
            });
        }
        res.status(201).json({
            messaggio: 'Utente salvato correttamente',
            oggetto: res
        });
    });
});



via Max Bertoli

No comments:

Post a Comment