mercredi 30 décembre 2015

Can't retrieve data from mongodb

I am trying to take a value from user in an input field of my index.html page and then using that value to query my mongodb collection to retrieve data. But as I print my returned object on the server side I see the object 'undefined' can't figure out why. I am using node, express, mongoose, mongodb, body parser.

Below is my server code.

var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/MyDB');

// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json 
app.use(bodyParser.json());
var FormSchema = new mongoose.Schema({

    title: String,
    degrees: [String]
}, { collection: "university" });


app.get("/", function(req, res) {
    res.sendFile('index.html', { root: '/Users/../Desktop/SimpleNode/'});
});

    app.post("/", function (req, res) {

    var queryuser = req.body.queryuser;

    var Form = mongoose.model("Form", FormSchema);


    var query = Form.find({ 'degrees':{$in: [queryuser]}});


    query.select('title');

    // execute the query at a later time
    query.exec(function (err, Form) {
        if (err) return handleError(err);
        console.dir(Form.title);

    })
});

http.createServer(app).listen(3000);

I am able to get the value from the front end as when I debug I see at the server side the value of the variable queryuser is what the user typed in. But at the line console.dir(Form.title); where I try to check my returned result object I get undefined. I even tried this by hard coding the query yet undefined.

And below is index.html

<html>
<body>

<form action="/" method="POST">
    <label>Add your search here.</label>
    <input type="text" name="queryuser" />
    <input type="submit" name="submit" value="make post req"/>

</form>

</body>
</html>




Aucun commentaire:

Enregistrer un commentaire