MongoDB:find({_ id:0})。toArray返回undefined

时间:2016-10-21 16:28:59

标签: javascript node.js mongodb

我是MongoDB和Node的初学者,正在从事一个项目。我有4个单选按钮代表用户答案。我已将正确答案存储在MongoLabs数据库中,我检索并登录app.get()函数。我想根据这些正确答案检查用户答案。但是,当我尝试find({_id:0}).toArray(function( (req,result)时,我会在控制台中获得undefined

的index.html

<!DOCTYPE html>
<head>
    <title>Online Testing Website</title>
</head>
<body>
<div id="question">
    <p>This is my first question</p>
    <br>
</div>
<div id="answer">
    <form action="/answer" method="get">
        <input id="a" type="radio" name="ans" value="A" >A<br>
        <input id="b" type="radio" name="ans" value="B" >B<br>
        <input id="c" type="radio" name="ans" value="C" >C<br>
        <input id="d" type="radio" name="ans" value="D" >D<br><br><br>
        <button type="submit">Submit</button>
    </form>
</div>

<script type="text/javascript" src="./server.js"></script>    

</body>
</html>

server.js:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
var path = require('path');
var mongo = require('mongodb').MongoClient;
//var client = require('socket.io').listen(8080).sockets;

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

var db;

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

mongo.connect('mongodb://deodhar:deodhar@ds015636.mlab.com:15636/correct-answers', function (err, database) {
    if(err){
        return console.log('mongo connect if: ' + err);
    }
    db = database;
    app.listen(8080, function () {
        console.log("Listening on 8080");
    });
});


app.get('/answer', function (req,res) {
    var answerUser = req.query;
    console.log("User answer: " , answerUser);
    var cursor = db.collection('answers').find({_id:0}).toArray(function (req,result) {
        var count = result.length;
        console.log(result[0]);
        if(result[0] === answerUser){
            console.log("correct!");
        }else{
            console.log("wrong");
        }
        res.redirect('/');
    });
});

0 个答案:

没有答案