猫鼬:所需的错误,但一切都已到位

时间:2017-06-27 08:45:33

标签: node.js mongoose

我目前正在使用Mongoose为Node.JS开发一个简单的Web应用程序,使用Mongoose连接到MongoDB,但我无法将其实际保存到数据库中。

我这样连接:

NSUTF8StringEncoding

打印出"连接到MongoDB"正如所料。 我的方案然后定义如下:

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");
    });

并且在我的脚本中需要我设置路线。这是我试图保存新文档的地方。

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);

但是我没有保存到数据库,而是收到错误:

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);
        });

    });

我无法找到有关此问题的任何信息,但我也没有真正看到错误。非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

从构造函数中删除"throw"参数:

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

另外,删除此:

{ useMongoClient: true }

这是一个"problem"的解决方案,只是不起作用。您将收到弃用警告,但这只是一个警告,而不是错误。