Cannot display value from Mongodb on my Jade page - node.js

I have the following route :
app.get('/dashboard', passportConf.isAuthenticated, userController.getBoardsCount,userController.getSharedBoardsCount, userController.getBoards);
This is the middleware code I'm using to get my values from MongoDB:
exports.getBoardsCount = function(req, res, next) {
var count = 0;
Room.count({
"owner": req.user._id
}, function(err, count) {
if (err) {
console.log(err);
}
if (count) {
req.count = count;
}
next();
console.log(count);
})
};
exports.getSharedBoardsCount = function(req, res, next) {
var sharedBoards = 0;
Room.count({
$and: [{"owner": {$ne: req.user._id}},{ users : req.user._id}]
}, function(err, sharedBoards) {
if (err) {
console.log(err);
}
if (sharedBoards) {
req.sharedBoards = sharedBoards;
}
next();
console.log(sharedBoards);
})
};
I can display the count on my jade file by using #{count}, but the sharedBoards is not appearing although it is being displayed in the terminal. I used #{sharedBoards} to display it in my Jade file. Can you guys please help me with this? I can't seem to find what is wrong.

exports.getBoards = function(req, res) {
Room.find({
users: req.user._id
}, function(
err,
rooms) {
if (err) {
return err;
}
res.render('account/dashboard', {
rooms: rooms,
count:req.count,
sharedBoards:req.sharedBoards
});
});
};
I mispelled sharedBoards.

Related

Express app.put / app.post outputs null values

I'm really new to node/express/mongoDB coding, and I have a slight problem with adding/updating values into mongoDB via node/express.
app.post('/', (req, res, next) => {
let data = {
first_value: req.body.first_value,
second_value: req.body.second_value,
};
dbase.collection("testDB").insertOne(data, (err, result) => {
if (err) {
console.log(err);
}
res.send('data added successfully');
});
});
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne({ _id: id }, {
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
app.put does not alter the values in DB, and app.post only adds "null" into every section of the new entry when I'm trying them with Postman. When I add new values with html form, the data is added correctly.
What is the problem with my code?
For app.post , can you provide me a screen shot of the way you are entering data and in which format e.g. , application/raw , application/x-www-form-urlencoded etc .
For app.put you need to correct the following things . The corrected code is as below ,
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne( id , { // put "id" instead of "{ _id: id }"
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
Hope you can get the point and this works for you .

Unable to delete data from mongoDB

Im using POSTMAN to delete contact using id and it returns
{
"n": 0,
"ok": 1
}
This is my delete code so far
router.delete('/contact/:id', (req, res, next) => {
contact.remove({ _id: new objectId(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
You need to pass the _id value as an ObjectID, not a string:
var mongodb = require('mongodb');
router.delete('/contact/:id', (req, res, next) => {
contact.deleteOne({ _id: new mongodb.ObjectID(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
id !== _id
change :id in your route to :_id and you should be fine.

What is the simplest and/or best way to send data between routes in node.js express?

My setup is like this:
I get data from omDB using a omdb lib from github, this whole parts looks like this:
router.post('/search', function(req, res) {
var omdb = require('omdb');
var title = req.body.title;
omdb.get( {title: title}, true, function(err, movie){
if(err) {
return console.log(err);
}
if(!movie) {
return console.log('No movie found');
}
//console.log('%s (%d)', movie.title, movie.year);
result = movie.title+movie.year+movie.poster;
console.log(result);
res.redirect('/result');
})
});
And then i want to use the result from that post request in another route:
router.get('/result', function(req, res) {
res.render('result', { title: title});
});
What is the best and hopefully simplest approach to do this, consider that I am a node.js noob.. :)
Assuming you're using express.js, you could use the session middleware:
router.post('/search', function(req, res) {
var omdb = require('omdb');
var title = req.body.title;
omdb.get( {title: title}, true, function(err, movie){
if(err) {
return console.log(err);
}
if(!movie) {
return console.log('No movie found');
}
//console.log('%s (%d)', movie.title, movie.year);
req.session.result = {
title: movie.title,
year: movie.year,
poster: movie.poster
};
res.redirect('/result');
})
});
then:
router.get('/result', function(req, res) {
if (req.session.result) {
var result = req.session.result;
req.session.result = null;
res.render('result', { movie: result });
}
else {
// Redirect to error page.
}
});

PUT and DELETE always route to GET in Node + Express

I'm a beginner in Node/Express. I tried to make an CRUD application but stuck at update and delete. I think my router code is problematic but I don't know why. The following code is in my controller, everything works but PUT and DELETE. It always route to GET. I tried to use next(); but it returns this error: Can't set headers after they are sent..
I can make the delete works by using GET /:company_id/delete but it's not a good and standardized solution. How can I get update and delete process worked?
'use strict';
var Companies = require('../../models/companies');
module.exports = function (router) {
// INDEX
// accessed at GET http://localhost:8000/companies
router.get('/', function (req, res) {
Companies.find(function(err, model) {
if (err) {
res.send(err);
}
else {
res.format({
json: function () {
res.json(model);
},
html: function () {
res.render('companies/index', model);
}
});
}
});
});
// CREATE VIEW
// accessed at GET http://localhost:8000/companies/create
router.get('/create', function (req, res) {
res.render('companies/create');
});
// CREATE DATA
// accessed at POST http://localhost:8000/companies
router.post('/', function (req, res) {
var name = req.body.name && req.body.name.trim();
var type = req.body.type && req.body.type.trim();
// VALIDATION
if (name === '') {
res.redirect('/companies/create');
return;
}
var model = new Companies({name: name, type: type});
model.save(function(err) {
if (err) {
res.send(err);
}
else {
res.redirect('/companies');
}
});
});
// READ
// accessed at GET http://localhost:8000/companies/:company_id
router.get('/:company_id', function(req, res) {
Companies.findById(req.params.company_id, function(err, model) {
if (err) {
res.send(err);
}
else {
res.render('companies/read', model);
}
});
});
// UPDATE VIEW
// accessed at GET http://localhost:8000/companies/:company_id/edit
router.get('/:company_id/edit', function(req, res) {
Companies.findById(req.params.company_id, function(err, model) {
if (err) {
res.send(err);
}
else {
res.render('companies/edit', model);
}
});
});
// UPDATE DATA
// accessed at PUT http://localhost:8000/companies/:company_id
router.put('/:company_id', function(req, res) {
Companies.findById(req.params.company_id, function(err, model) {
if (err) {
res.send(err);
}
else {
model.name = req.body.name;
model.type = req.body.type;
model.save(function(err) {
if (err) {
res.send(err);
}
else {
res.redirect('/companies');
}
});
}
});
});
// DELETE
// accessed at DELETE http://localhost:8000/companies/:company_id
router.delete('/:company_id', function (req, res) {
Companies.remove({ _id: req.params.company_id }, function(err) {
if (err) {
res.send(err);
}
else {
res.redirect('/companies');
}
});
});
};
HTML forms only support GET and POST. XMLHTTPRequest supports PUT and DELETE however, so you may have to go that route OR use something like method-override to allow HTML forms to submit using other HTTP verbs.

NodeJS / Mongoose Filter JSON

I am building a JSON API with ExpressJS, NodeJS and Mongoose:
Input -> id:
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}, function (err, product) {
if (!err) {
console.log(product);
return res.send(product);
} else {
return console.log(err);
}
});
});
It shows well the JSON:
[{"_id":"B443U433","date":"2014-08-12","reference":"azerty","file":"087601.png","
....:.
{"_id":"HGF6789","date":"2013-09-11","reference":"azerty","file":"5678.pnf","
...
I just want to display the _id in the JSON, so it is good when I have lots of data.
How I can do that? Something like a filter?
You can chain calls to select and lean to retrieve just the fields you want from the docs you're querying:
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}).select('_id').lean().exec(
function (err, product) {
if (!err) {
console.log(product);
return res.send(product);
} else {
return console.log(err);
}
});
});
You would have to iterate over your "products" object to obtain the ids
Something like this:
(Disclaimer: I haven't tested this)
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}, function (err, product) {
if (!err) {
console.log(product);
var ids = new Array();
for(var i = 0; i < product.length; i++){
ids.push(product[i]._id);
}
return res.send(JSON.stringify(ids));
} else {
return console.log(err);
}
});
});
--Edit
Also, "products" may already be a JSON string. You may want to parse it before looping.
product = JSON.parse(product);
Other answers are true but I think it's better to limit data in mongoose like this :(it's same as mongo shell commands)
app.get('/folder/:id', function (req, res){
Cars.find({reference: req.params.id} ,{ _id : true } ,function (err, product) {
if (!err) {
console.log(product);
} else {
console.log(err);
}
});
});

Resources