nodejs pass same variable in two differents middlwares - node.js

in my app file i have two post middlwares
app.post('/check',urlencodedParser,function (req, res) {
var date_entre_user=req.body.dateentry;
var date_sortie_user=req.body.datesortie;
var idroom=req.body.room;
let sql=`SELECT * FROM reservation WHERE idchambre = ${req.body.room}`;
let query=db.query(sql,(err,result)=>{
datesortieuser=dateFormat(date_sortie_user,"isoDaTteTime");
dateentreuser= dateFormat(date_entre_user,"isoDateime");
app.post('/submit',urlencodedParser,function (req, res) {
.numtele,
email: req.body.email
}
/* let clt = {
nom: req.body.nom,
prenom : req.body.prenom,
cin: req.body.cin,
ville: req.body.ville,
pays: req.body.pays,
tele: req.body
let sql2 = 'INSERT INTO client SET ?'
db.query(sql2, clt,function (err, result) {
if (err) throw err;
console.log("1 client inserted");
});
let sql3 =`SELECT idclient FROM client WHERE nom = ${req.body.nom}`;
db.query(sql3,function (err, result) {
if (err) throw err;
console.log(result);
});
but when i use the variable date_entre_user in the second middleware post i got variable undefined
how can i do it?

The variable you mentioned is defined only in your first .post() method, so it isn't in scope in the second one.
If you want to pass data from one middleware function to another, a good way is to use req.locals, adorning the req object with the data you're passing. Something like this.
/* in one function */
if (!req.locals) req.locals = {}
req.locals.date_entre_user = quelqueChose
and then in the next function, you can refer to that same item.

Related

Projection in .find() not working for MongoDB/Express [duplicate]

This question already has answers here:
batchSize field name ignored in Field Projection
(2 answers)
Closed 4 years ago.
I have an express app that's supposed to query my MongoDB database, then return only certain fields of the result. My code for this currently looks like this:
app.get('/stored', (req, res) => {
let pollId = req.query.id;
let pollCursor = db.collection(collName).find({"_id": ObjectId(pollId)}, {"_id": false, "pollName": false}).toArray((err, data) => {
if(err) return err;
let dataObj = data[0];
console.log(dataObj);
});
});
I expect to recieve a data object that contains all fields except the '_id' and 'pollName' fields. However, the object I get still contains both these fields, as well as all the other fields. What am I doing wrong?
The first you have to test like this:
app.get('/stored', (req, res) => {
let pollId = req.query.id;
res.send(pollId)
return;
});
if pollId match with pollId from client send, it's fine. You should create a query to find like this:
let query = {_id: pollId}
This is my code, hope help you
// https://tudiendanhngon.herokuapp.com/author/detail?id=5adc963c7b76157c65d3b1d9
app.get("/author/detail", function (req, res) {
var id = req.query.id;
var query = {_id: id};
db.collection(COLLECTION_AUTHORS).find(query).exec(function (err, author) {
if (err) {
res.send("Error")
} else {
res.json(author);
}
});
});

how to send a message from inside a callback function with mongodb in nodejs

I am coding a basic project manager, nothing fancy. I am writing the page where the project is created (with AngularJS) and am sending all the $scope to /create (the backend is Express.js). The router gets the JSON perfectly, and save it to a local MongoDB without problems.
My problem is that I want to set a message telling that the project was created successfully and send it back to AngularJS. This is my code.
router.js
module.exports = function(app, db) {
app.post('/create', function (req, res) {
var create = require("./../scripts/create")(req, res, db);
console.log(create); //just for testing whether I can receive the message.
});
}
create.js
module.exports = function(req, res, db) {
db.collection('projects').insert(req.body.project, function(err, docs) {
if (err) throw err;
return 'Project created.'; //I want to return this string.
});
};
I don't know how to return something from inside the db.collection.insert's callback function.
So you have to remember that anonymous function calls in JavaScript are not assigned to anywhere. They are passed, and then lost. This is usually why we don't really have return statements in them.
var x = function () { return y }; gives x the value of y but since there is never an assignment of the value of a callback, a return statement is meaningless. Callbacks, no matter if they have a return value, will not give you a value. They may feed that return value up to the function that they were given to, but they are entirely lost to you.
The way to get around this is to do some trickery with the scope. Basically what you want to do is 'bump' the value you want to return up a scope you can assign and then return it there. For example, you can do this:
module.exports = function(req, res, db) {
var stringToReturn;
db.collection('projects').insert(req.body.project, function(err, docs) {
if (err) throw err;
stringToReturn = 'Project created.'; //I want to return this string.
});
return stringToReturn;
};
This will work because the return value gets bound to module.exports, which is in turn bound to the result of
var create = require('./create');
console.log(create('something')) //should log 'Project created.'
Solved!!
Router.js
module.exports = function(app, db) {
app.post('/create', function(req, res) {
var create = require("./../scripts/create")(req, res, db);
});
});
Create.js
module.exports = function(req, res, db) {
db.collection('projects').insert(req.body.project, function(err, records) {
if (err) throw err;
res.send("Project created.");
});
};
Now Angular is receiving the response from the server.

MongoDB is not producing output with Node.js

I am having trouble getting the output of a MongoDB query. When I call the save method:
db.users.save({email: "test#gmail.com", password: "test", sex: "male"},
function(err, saved) {
});
The code works, and stores the entry. However, the function (err, saved) isn't called, as far as I know. When I run this code:
var mongojs = require("mongojs");
var MONGOHQ_URL="mongodb://testUser:testPassword#paulo.mongohq.com:10085/app********";
app.get('/', function(request, response) {
var m = "hello";
var databaseUrl = MONGOHQ_URL;
var collections = ["users"];
var db = mongojs.connect(databaseUrl, collections);
var d = db.users.find({"sex":"male"}).limit(1);
response.send(d.email);
});
Then I get nothing. Is there something I'm missing?
var d = db.users.find({"sex":"male"}).limit(1) has no call back function so it goes out of scope and you dont see the response.
Two things first off i would use findOne instead of limit(1) and secondly you are missing the callback function, try this
db.users.findOne({"sex":"male"}, function (err, result) {
if(err){
console.log(err);
}else{
console.log(result);
//then do your response here
response.send(result.email);
}
});
Hope that makes sense.

How to add an array of objects to parse.com db?

I'm developing an application and need to add many items at a time.
How can I do that with node.js?
This is the npm module for parse.com but there is no method like
insertAll("Foo", [objs...], ...)
I don't want to insert single object every time.
Write a convenience function that interfaces between your application and parse.com. You will have to write the iteration code once (or debug mine)
var async = require('async');
var parseApp = require('node-parse-api').Parse;
var APP_ID = "";
var MASTER_KEY = "";
var parseApp = new Parse(APP_ID, MASTER_KEY);
function insertAll(class, objs, callback){
// create an iterator function(obj,done) that will insert the object
// with an appropriate group and call done() upon completion.
var insertOne =
( function(class){
return function(obj, done){
parseApp.insert(class, obj, function (err, response) {
if(err){ return done(err); }
// maybe do other stuff here before calling done?
var res = JSON.parse(response);
if(!res.objectId){ return done('No object id') };
done(null, res.objectId);
});
};
} )(class);
// async.map calls insertOne with each obj in objs. the callback is executed
// once every iterator function has called back `done(null,data)` or any one
// has called back `done(err)`. use async.mapLimit if throttling is needed
async.map(objs, insertOne, function(err, mapOutput){
// complete
if(err){ return callback(err) };
// no errors
var objectIds = mapOutput;
callback(null, objectIds);
});
};
// Once you've written this and made the function accessible to your other code,
// you only need this outer interface.
insertAll('Foo', [{a:'b'}, {a:'d'}], function(err, ids){
if(err){
console.log('Error inserting all the Foos');
console.log(err);
} else {
console.log('Success!);
};
});

Send multiple DB query results to a single view using Express

I have a dashboard view ( dashboard.jade ) that will display two panels with different information, all that info should be retrieved from a database and then sent to the view.
Let's say i have a route file ( document.js ) with two actions defined:
exports.getAllDocuments = function(req, res){
doc = db.model('documents', docSchema);
doc.find({}, function(err, documents) {
if (!err) {
// handle success
}
else {
throw err;
}
});
};
exports.getLatestDocumentTags = function(req, res){
tags = db.model('tags', tagSchema);
tags.find({}, function(err, docs) {
if (!err) {
// handle success
}
else {
throw err;
}
});
};
These functions would only serve the porpuse of retrieving data from the database.
Now i would like to send that data to the dashboard view from my dashboard.js route file under exports.index function where i render my dashboard view.
The problem is, since the db calls will be async i wouldn't have access to the data before i could call the view.
I guess i could have an action that simply did all my db calls and through callbacks deliver all the data at once to the view but that would make my data retrieval actions not reusable.
I'm really confused on how to tackle this problem correctly, probably i'm getting this async thing all wrong. Can someone give me some hints on how to do this properly ?
Here's something to pique your interest.
//Check out the async.js library
var async = require('async');
//Set up your models once at program startup, not on each request
//Ideall these would be in separate modules as wel
var Doc = db.model('documents', docSchema);
var Tags = db.model('tags', tagSchema);
function index(req, res, next) {
async.parallel({ //Run every function in this object in parallel
allDocs: async.apply(Doc.find, {}) //gets all documents. async.apply will
//do the equivalent of Doc.find({}, callback) here
latestDocs: async.apply(Tags.find, {})
], function (error, results) { //This function gets called when all parallel jobs are done
//results will be like {
// allDocs: [doc1, doc2]
// latestDocs: [doc3, doc4]
// }
res.render('index', results);
});
}
exports.index = index;
};
Try some more tutorials. If you haven't had the "a ha" moment about how async programming works in node, keep going through guided, hand-held tutorials before trying to write brand new programs without guidance.
//Check out the async.js library and mangoose model
var mongoOp = require("./models/mongo");
var async = require('async');
router.get("/",function(req,res){
var locals = {};
var userId = req.params.userId;
async.parallel([
//Load user Data
function(callback) {
mongoOp.User.find({},function(err,user){
if (err) return callback(err);
locals.user = user;
callback();
});
},
//Load posts Data
function(callback) {
mongoOp.Post.find({},function(err,posts){
if (err) return callback(err);
locals.posts = posts;
callback();
});
}
], function(err) { //This function gets called after the two tasks have called their "task callbacks"
if (err) return next(err); //If an error occurred, we let express handle it by calling the `next` function
//Here `locals` will be an object with `user` and `posts` keys
//Example: `locals = {user: ..., posts: [...]}`
res.render('index.ejs', {userdata: locals.user,postdata: locals.posts})
});

Resources