Lenco
Lenco

Reputation: 27

Mongoose: required error, but everything is in place

I am currently developing a simple web application for online polls with Node.JS using Mongoose to connect to a MongoDB, but I cannot get it to actually save to the database.

I connect like this:

var mongoDB = 'mongodb://localhost/poll_database';
    mongoose.connect(mongoDB, { useMongoClient: true });
    mongoose.Promise = global.Promise;
    mongoose.set('debug', true);
    mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
    mongoose.connection.once('open', function() {
      console.log("Connected to MongoDB");
    });

It prints out "Connected to MongoDB" as expected. My scheme is then defined like this:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var answer = new Schema({
    text: {type: String, trim: true},
    count: {type: Number, default: 0}
},{ _id : false });


var poll = new Schema({
    question: String,
    answers: [answer],
    userDefinedAnswers: {type: Boolean, default: true},
    pollcode: {type: String, minlength: 6, maxlength: 6, unique: true, index: true}
}, { collection: 'polls' });

for (var i in poll.paths) {
    var attribute = poll.paths[i]
    attribute.required(true);
}

module.exports = mongoose.model('Poll', poll);

and required in my script where I set up the routes. This is where I am trying to save a new document.

app.post('/create', function(req, res) {
        var question = req.body.question;
        var options = req.body.options.split(",");
        var addingAllowed = req.body.addingAllowed;

        var poll = new Poll({question: question, userDefinedAnswers: addingAllowed, pollcode: generatePollcode()}, "throw");

        for ( var i = 0; i < options.length; i++ ) {
            poll.answers.push({text: options[i], count: 0});
        }


        console.log(poll); // prints out exactly what I want

        poll.save(function(err, doc) {
            if ( err ) throw err;
            res.redirect('/vote.html?code=' + doc.pollcode);
        });

    });

But instead of saving to the database I get an error:

ValidationError: Poll validation failed: pollcode: Path `pollcode` is required.,
userDefinedAnswers: Path `userDefinedAnswers` is required.,
question: Path `question` is required.,
answers: Path `answers` is required.

I couldn't find any information on this issue, but I don't really see what's wrong either. Help is greatly appreciated.

Upvotes: 0

Views: 198

Answers (1)

robertklep
robertklep

Reputation: 203304

Remove the "throw" argument from the constructor:

var poll = new Poll({question: question, userDefinedAnswers: addingAllowed, pollcode: generatePollcode()});

Also, remove this:

{ useMongoClient: true }

It's a solution to a "problem" that just doesn't work. You'll get a deprecation warning, but that's just a warning, not an error.

Upvotes: 1

Related Questions