Dynamic key value in find statement Mongodb and Nodejs - node.js

I wonder why does I can't get result on Find query with dynamic key object as parameter.
My goal is to make searching Api with dynamic key and value parameter.
as I always get an empty result with this :
module.exports = function (app, db) {
app.post('/getUser/', function(request, response){
/* Preparing dynamic params */
var param = {
request.body.key : /request.body.value/
};
db.collection('user').find(param).toArray(function(err, result){
console.log(result);
})
})
}
But I can get proper result with "hard coded" parameter like this :
module.exports = function (app, db) {
app.post('/getUser/', function(request, response){
db.collection('user').find({ name : /John/ }).toArray(function(err, result){
console.log(result);
})
})
}
Any answer will be highly appreciated! Thank you.

Related

nodejs pass same variable in two differents middlwares

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.

assigning mongoose result feild value to vriable in express

i am trying to assign value of a feild from momgoose to a variable which would be used as value to another feild in another schema which is as follows.
function getNextSequence() {
var x = null
relcounter.findOne({"name":"cabi"},'seq', function (err, configs) {
x=configs.seq
console.log("##"+x)
})
console.log(x)
}
X is coming out to be null
Also i need this value of x to add to another feild which is as follows
relconf.update(
{name:"css"},
{ $push: { relations: {id:getNextSequence(),name:req.body.name,divId:"name_div"} } }
Basically ineed the function getNextsequence to return the value of seq feild and assign to id feild
can anyone suggest proper code and reason for null value for getNextSequence()
It useless wrap it in function, you must create include callbacks or Promises chaining. So you need read about asynchronous JavaScript https://www.sitepoint.com/javascript-goes-asynchronous-awesome/ For example:
//callbacks example
...
app.get('/', function(req, res){
//parse request params
...
relcounter.findOne({"name": name},'seq', function (err, configs) {
if(err) {
throw err;
}
res.send(configs.seq);
});
});
//promise example
...
app.get('/', function(req, res){
//parse request params
...
relcounter.findOne({"name": name},'seq')
.then(function(configs){
res.send(configs.seq);
})
.catch(function(err)=>{
throw err;
})
});

Storing Collection result from mongoDB in Node

I am new to node and I have read the data from mongoDB successfully.
But I would like to store the whole data from the Collection into a variable in nodejs as I would like to use them in the index page.
I do not know how to store it.
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
seriescollection = db.collection('series');
});
var findseries = function (db, callback) {
var cursor = db.collection('series').find();
cursor.each(function (err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
//insertDocument(db, function () {});
findseries(db, function () {
db.close();
});
});
My sample JSON object in MongoDb is
{
"_id" : "b835225ba18",
"title" : "Name",
"imageurl" :"https://promotions.bellaliant.net/files/Images/TMN/Ballers-June2015.jpg",
"namespaceId" : "UNI890"
}
I would like to access all the fields and create a page based on the fields that I have stored. I need to access all the fields and that is my main goal.
This is a pet project I am working on a leisure time to learn MEAN stack a bit.
Thanks a lot for your help!!!!
There's a few issues with this code, but I think what you're looking for is the toArray method:
var findseries = function (db, callback) {
db.collection('series').find().toArray(function(err, allTheThings) {
// Do whatever with the array
// Spit them all out to console
console.log(allTheThings);
// Get the first one
allTheThings[0];
// Iterate over them
allTheThings.forEach(function(thing) {
// This is a single instance of thing
thing;
});
// Return them
callback(null, allTheThings);
}
}
More here: https://docs.mongodb.org/manual/reference/method/cursor.toArray/
And here: https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray

In node js how to get the result of the other module method in current module

ModuleTwo.js
exports.getNotificatiosById = function (notificationId) {
db.get(notificationId, function (err, doc) {
if(!err){
return true;
}
});
};
In modulelOne i need to get the result of the moduleTwo method.If moduleTwo method doesn't have the database query function means i can get that method result like below in moduleOne
var res=require('./lib/moduleTwo').getNotificatiosById;
If that db.get method has the synchronize method means i can do the query like
db.getSync(id);
Is there any other way to get the result of my moduleTwo method.Now i'm trying like below.Is it correct
moduleOne.js
var moduleTwo=require('./lib/moduleTwo');
moduleTwo.getNotificatiosById(id,function(err,res){
if(!err){
console.log('Result of the 2nd module is '+res);
}
});
You need to change getNotificatiosById to take a callback
exports.getNotificatiosById = function (notificationId,callback) {
db.get(notificationId, function (err, doc) {
if(!err){
callback(doc);
return true;
}
});
};
Then call it like
var moduleTwo=require('./lib/moduleTwo');
moduleTwo.getNotificatiosById(id,function(res){
console.log('Result of the 2nd module is '+res);
});

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