Put data into mongodb's query in Expressjs - javascript

I have a query in Expressjs like this :
collection.find({location : {$near: [106.688227,10.774266], $maxDistance: 0.01}},function(e, docs) {
res.json(docs);
});
It works well but when I get the parameter from the request to put it in the query , it does not work :
router.get('/locations', function(req, res) {
var lat = req.param('lat');
var lng = req.param('lng');
var radius = req.param('radius');
var db = req.db;
var collection = db.get('location');
collection.find({location : {$near: [lng,lat], $maxDistance: radius}},function(e, docs) {
res.json(docs);
});
});
I how can replace "lng","lat" and "radius" into the query?
Thanks.

Related

How to update record using id in nodejs

I am new in Node Js and trying to learn it. I am currently follow this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ but its incomplete.
I want, if I click on any user from the list of users, it will take me to new page and show the record in form for update. I don't know how to send data onclick, find the record from the db and show it inside a form to update.
Here is the index file with all the functions:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*Get Hello world page*/
router.get('/helloword', function(req, res){
res.render("Helloworld", {title:'Hello, World!'});
});
/*Get UserList*/
router.get('/userlist', function(req, res){
var db = req.db;
var collection =db.get('usercollection');
collection.find({}, {}, function(e, docs){
res.render('userlist',{
"userlist": docs
});
});
});
/*Get New User Page*/
router.get('/newuser', function(req, res){
res.render('newuser',{title: 'Add New User'})
});
/* POST to Add User Service */
router.post('/adduser', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : userName,
"email" : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
res.redirect("userlist");
}
});
});
module.exports = router;
Thanks in advance please help me for guidance
It looks like you want to use findAndModify (docs)
Using your code you could implement an update route like so.
router.post('/user/:userId', function (req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
collection.findAndModify(
{_id: req.query.userId}, // query
[['_id', 'asc']], // sort order
{
$set: {
"username": userName,
"email": userEmail
}
}, // replacement
{}, // options
function (err, object) {
if (err) {
console.warn(err.message); // returns error if no matching object found
} else {
console.dir(object);
}
});
});
However this does not have any validation to make sure that the user has the correct permissions to update this, make sure you add something like the query
{$and: [{_id: req.query.userId}, {createdBy: req.user}]}

Jade/Node database data not showing

I'm attemting to create an application to make restraunt reservations with Node, but currently my data from the database is not showing on the page. Here is the jade file of the page that is meant to display the data:
extends layout
block content
h1.
Reservations
ul
each reservation in reservations
li= reservation.lastName
li= reservation.numberOfPeople
Here is my index.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/reservations', function(req, res) {
var db = req.db;
var collection = db.get('freshStart');
collection.find({},{},function(e,docs){
res.render('reservations', {
"reservations" : docs
});
});
});
router.get('/makeReservation', function(req, res){
res.render('makeReservation', { title: 'Make a reservation'});
});
router.post('/makeReservation', function(req, res){
var db = req.db;
var lastName = req.body.lastName;
var numberOfPeople = req.body.numberOfPeople;
var time = req.body.myTime;
var date = req.body.myDate;
var collection = db.get('freshStart');
collection.insert({
"lastName" : lastName,
"numberOfPeople" : numberOfPeople,
"time" : time,
"date" : date
}, function(err, doc) {
if(err) {
res.send("There was a problem adding the information to the database", err.toString());
} else {
res.redirect("reservations");
}
});
});
module.exports = router;
Yet when I load the page, it only shows the title but no database info. I've queried the data in cmd and it comes up with two entries. What am I doing wrong?
The error was I was refrencing the wrong part of the database. This was my code:
router.get('/reservations', function(req, res) {
var db = req.db;
var collection = db.get('freshStart');
collection.find({},{},function(e,docs){
res.render('reservations', {
"reservations" : docs
});
});
});
What I should have been doing is this:
router.get('/reservations', function(req, res) {
var db = req.db;
var collection = db.get('reservations');
collection.find({},{},function(e,docs){
res.render('reservations', {
"reservations" : docs
});
});
});

how to send a value to database through a separate module?

I have a basic express project created. And I've created a file called lib/userhandler.js inside root folder.
//lib/userhandler.js
exports.addUser = function(req, res){
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var uName = req.body.username;
var uEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : uName,
"email" : uEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// If it worked, set the header so the address bar doesn't still say /adduser
//res.location("userlist");
// And forward to success page
res.redirect("userlist");
}
});
}
In my routs/users.js file, whenever the users page is loaded I want to send name and the mail values throught userhandler.js to the database.
//routes/users.js
var express = require('express');
var router = express.Router();
var User = require("../node_modules/SimpleExpress/routes/userhandler.js");
var name = "testuser6";
var mail = "testuser6#testdomain.com";
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
User.addUser(name, mail);
});
module.exports = router;
When I try to load users page it shows "Can't set headers after they are sent."
Thank You
You should try to return the error from your db to your route handler through a callback like this :
//routes/users.js
var express = require('express');
var router = express.Router();
var User = require("../node_modules/SimpleExpress/routes/userhandler.js");
var name = "testuser6";
var mail = "testuser6#testdomain.com";
/* GET users listing. */
router.get('/', function(req, res, next) {
User.addUser(name, mail, function(err, doc) {
if(err) {
res.send("There was a problem adding the information to the database.");
} else {
res.redirect("userlist");
}
});
});
//lib/userhandler.js
exports.addUser = function(name, mail, cb){
// Set our internal DB variable
var db = req.db;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : name,
"email" : mail
}, function (err, doc) {
cb(err, doc);
});
}
You shouldn't insert the request and response objects as parameters of the function addUser(). They should be in the router callback function. I added a new parameter to the function, so that you can pass the database as a parameter thanks to the router which receives the request object as a parameter.
//lib/userhandler.js
exports.addUser = function(uName, uEmail, db){
var collection = db.get('usercollection');
var result = true;
collection.insert({
"username" : uName,
"email" : uEmail
}, function (err) {
if (err) {
result = false;
}
});
return result; // true or false
}
I changed the code here also, so that the name and email variables can be received from the req and res parameters.
//routes/users.js
var express = require('express');
var router = express.Router();
var User = require("../node_modules/SimpleExpress/routes/userhandler.js");
//var name = "testuser6"; // I don't think you need this
//var mail = "testuser6#testdomain.com"; // and this
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
var db = req.db;
var name = req.body.username;
var mail = req.body.useremail;
if(!User.addUser(name, mail, db)) {
res.send("There was a problem adding the information to the database.");
return;
}
res.redirect('userlist');
});
module.exports = router;
I haven't tested the code because I really don't have time but I hope it works fine.

chaining database queries using promise in node.js

I'm trying to use the spread method to accumulate promised results that I've read in this thread with Q.js. It works in another block of code but not in the following app.get example. I want to chain queries using Sequelize and mongoose and pass all the returned data to the spread method. Here's my attempt:
var db = require('./db/managedb'); // Sequelize
var mongo_models = require('./db/mongo_model')(mongoose);
var WB = mongo_models.Webdata,
Est = mongo_models.Estimate;
app.get('/p/:tagId', function(req, res){
var filename = req.param("tagId");
var mysql = db.db.query('CALL procedure()').then(function(rows) {
console.log(rows);
}); // Sequelize
var nosql = WB.find().exec(function(err,k){
console.log(k);
}) // Mongoose
var nosql2 = Est.find().exec(function(err,la){
console.log(la);
}) // Mongoose
Q.try(function(){
return mysql
}).then(function(mysqls){
return [ mysqls,nosql]
}).then(function(mysqls,nosqls){
return [mysqls,nosqls,nosql2]
}).spread(function(mysqls,nosqls,nosql2s){
res.render(filename+'.html', {my:mysqls,wb:nosqls,est:nosql2s})
}).catch(function(error){
console.log('fail')
})
})
I'm just getting a blank page with Cannot GET /p/5 and there's no "fail" shown in the console.log. Here's my original code that works, but it's suffering from callback hell.
app.get('/p/:tagId', function(req, res){
var filename = req.param("tagId");
db.db.query('CALL procedure()').then(function(rows) {
WB.find().exec(function(err,wb){
Est.find().exec(function(err,est){
res.render(filename+'.html', {my:rows,wb:wb,est:est})
})
})
}).catch(function (error) {
console.log('own: database error');
})
})
You can try using them as proxies:
app.get('/p/:tagId', function(req, res){
var filename = req.param("tagId");
var rows = db.db.query('CALL procedure()');
var wb = WB.find().exec();
var est = Est.find().exec();
Promise.props({my: rows, wb: wb, est: est}).then(function(obj){
res.render(filename+'.html', obj)
}).catch(function (error) {
console.log('own: database error'); // not sure I'd just supress it
});
});
Bluebird is already available through sequelize if you don't have it in your project.
Alternatively, you don't have to put them in specific variables:
app.get('/p/:tagId', function(req, res){
var filename = req.param("tagId");
Promise.props({
my: db.db.query('CALL procedure()'),
wb: WB.find().exec(),
est: Est.find().exec()
}).then(function(obj){
res.render(filename+'.html', obj);
}).catch(function (error) {
console.log('own: database error'); // not sure I'd just supress it
});
});

PULL DATA (count) FROM MONGODB AND DISPLAY IT in a web app?

I'm trying to pull the number of documents in mongodb db and display it in my Application home page... I found this code that it works well but returns the list of all documents (users List):
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs }); }); });
I don't understand the part function(e,docs)!
I tried the following code to get the number of documents but it doesn't work:
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.count({},{},function(e,docs){
res.render('userlist', {
"userlist" : count }); }); });
Thank you for help
You can try for this:
You have to get the length from the callback docs..
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs.length }); }); });

Categories