I am a Nodejs newbie and am trying to search my mongolab database for an entry(that I know exists) using data from a form entry. Here is my code:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;
var app = express();
app.set('view engine', 'ejs')
const port = 3000;
MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
if(err) return console.log(err);
db = database
app.listen(port, function() {
console.log('Server started at port:'+port);
});
});
// var urlencodedParser = bodyParser.urlencoded({ extended:false });
app.use(bodyParser.urlencoded({extended:false}));
app.get('/', function(req, res) {
res.sendFile(__dirname+'/index.html');
});
app.all('/addUser', function(req, res) {
res.render('addUser');
db.collection('users').save(req.body, function(err, result) {
if (err) return console.log(err);
console.log('saved to database');
})
console.log(req.body);
});
app.get('/outputAll', function(req, res) {
db.collection('users').find().toArray(function (err, result) {
if (err) return console.log(err);
res.render('outputall', {users:result});
});
});
app.get('/Search', function(req, res) {
res.render('search');
var query = {}
console.log(req.body);
if (req.body.username)
{
console.log("true");
query.username = req.body.username;
}
db.collection('users').find({query}).toArray(function(err, result) {
if (err) return console.log(err);
console.log(1);
});
});
The search
part is meant to accomplish this objective. But I am not sure how to collect the query from my input form and pass it to the this app.get
and have it passed to the database where it is searched. Here is the Search
ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MY APP</title>
</head>
<body>
<div style="margin: 0 auto;width: 500px;">
<form action="/Search" method="GET" style="margin: 0 auto; width: 200px; margin-top: 100px;">
<input type="text" placeholder="Search" name="username" style="margin: 20px auto; font-size: 50px;">
<!-- <input type="file" name="picture"> -->
<button type="submit" style="margin: 20px auto; font-size: 50px;">Submit</button>
</form>
</div>
</body>
</html>
The output on the console when I run this is:
Server started at port:3000
{}
[]
{}
[]
I was expecting the {}
to be the form
data and the []
to be the result of searching the query in the database. Please help!
via Vineet Kaushik
No comments:
Post a Comment