Node Js (Returning null) - node.js

I have this function to retrieve a specific user from a mongo db:
exports.findById = function(req, res){
var id = req.params.id;
db.collection('Users', function(err, collection){
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item){
findPhotoByUserId(item._id, function(photo){
console.log('photo: ' + photo);
});
});
});
};
And this other to get the photo of the user, passing to it the Id of the user:
var findPhotoByUserId= function(userId, cb){
db.collection('Photos', function(err, collection){
collection.findOne({'userId': userId}, function(err, item){
if(!err)
cb(item);
});
});
};
Problem: the photo item is being null when i call the function "findById". However, if i put the explicit User Id here "collection.findOne({'userId': '522bae4a3ee1be8005000001'}....", the function returns the expected photo item.
Can someone help me about this issue?
Thanks!

I had the same problem. I got my code to work by using ObjectID in the 'mongodb' library:
var ObjectID = require("mongodb").ObjectID;
//more code here
query._id = { $gt: ObjectID(myId) }

Well, i solved my problem!
At this function:
var findPhotoByUserId= function(userId, cb){
db.collection('Photos', function(err, collection){
collection.findOne({'userId': userId.toString()}, function(err, item){
if(!err)
cb(item);
});
});
};
the 'userId' must be converted do a string.
Thanks!

Related

Is it possible to show the whole updated record instead of the updated field only?

So basically, I am creating an inventory management app and want to show the updated record to the user in the sense not just the field that was updated but the whole document itself. My question is
*How do I show the whole updated record instead of the updated field to the user ? *
I am using postman to test this api. This is my code and those with comments are what I have tried.
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
module.exports = {
/*getCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
var doc = findMultiple(db,req,function() {
db.close();
});
});
res.send(doc)
}*/
postCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
updateRecord(db, req, function() {
db.close();
});
//findMultiple(db, req, function(){
//db.close();
//});
});
res.send('Record Found. Now updating this document...' + itemDescrip + '
Record Updated. This is the new record with updated issueQty '
+ issueQty )
}
}
var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany(
{ 'Item Description': req.body.itemDescrip},
{
$set: { 'Issued QTY': req.body.issueQty }
}
,
function(err, results) {
console.log(results);
console.log('Done');
callback();
});
};
/*var findMultiple = function(db, req, callback){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
var cursor = db.collection('documents').find({'Issued QTY': issueQty, 'Item
Description': itemDescrip});
cursor.each(function(err,doc){
assert.equal(err,null);
if(doc != err){
console.log('Successfully queried');
console.log(doc);
return doc;
} else {
callback();
}
});
};*/
I have tried putting another function findMultiple to get the data and show the updated record in the response but it did not work and have thought about linking my query api and the update api together but am not sure how to go about it. Any help is appreciated, thanks!
You need to:
Inside updateRecord(), call the callback with the results object of the update operation
Inside postCollection(), the callback passed to updateRecord() will have access to the results object
postCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
updateRecord(db, req, function(results) {
res.send('Document...') //Do what you want with results here
db.close();
});
});
var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany(
{'Item Description': req.body.itemDescrip},
{$set: { 'Issued QTY': req.body.issueQty }},
function(err, results) {
console.log(results);
console.log('Done');
callback(results); //pass results to the callback
});
};

Express js use values from mongodb to outside of the query

I am new with express js and node js. I am wonder if its possible to do this or not.
1st thing I'm trying to get the count on 1 query.
2nd I query collection login. loop it and format and get the name values using ids.
I get undefined on count1 and I see it ommitted on the json response.
how do I pass the query returns outside of the query?
router.post('/logmein', function(req, res, next) {
var email = req.param('email');
var password = req.param('password');
var count1;
MongoClient.connect(MongoUrl, function(err, db) {
if (err) return;
db.collection('users').count({email: email,password: md5(password)}, function(err, count) {
count1 = count;
});
db.collection('login').find({email: email,password: md5(password)}).toArray(function(err, results){
console.log(results); // output all records
});
//use results
/*
foreach each results format with other info
var new_array;
*/
res.json({"success": true,"count":count1,new_array: new_array});
});
});
Async issues, you have to look more at it. Use the async module and then you will be able to fire the queries in parallel. Finally, you will have the results in the final callback. This snippet will fix your issue:
var async = require('async');
router.post('/logmein', function (req, res, next) {
var email = req.param('email');
var password = req.param('password');
var retResults;
var count1;
MongoClient.connect(MongoUrl, function (err, db) {
if (err) return;
async.parallel([
function(callback){
db.collection('users').count({ email: email, password: md5(password) }, function (err, count) {
return callback(err, count);
});
},
function(callback){
db.collection('login').find({ email: email, password: md5(password) }).toArray(function (err, results) {
return callback(err, results);
});
}
], function(err, results) {
if (err) {
// #todo: handle the error
}
count1 = results[0];
retResults = results[1];
//use results
/*
foreach each results format with other info
var new_array;
*/
res.json({ "success": true, "count": count1, new_array: new_array });
};
});
});
You need something like async.parallel to control the async flow of your nodejs application
async.parallel([
function(callback){ ... },
function(callback){ ... }
], function(err, results) {
// optional callback
};

How to use ensureIndex with geoJSON on node.js?

I'm very new to node.js and mongodb so any help would be appreciated. I have tried using ensureIndex before AND after the collection.update operation but either way it starts erroring out it seems.
Could someone point me in the right direction?
app.post("/", function(req, res){
var jsonObj = req.body;
var username = jsonObj['Username'];
var longitude = jsonObj['longitude'];
var latitude = jsonObj['latitude'];
var geoJsonObj = {'Username': username, location: {"type" : "Point", "coordinates" : [longitude, latitude]}};
//res.send(req.body);
mongo.Db.connect(mongoUri, function (err, db) {
if (err)
res.send(null);
db.collection('catchmerequests', function(err, collection) {
if (err)
res.send(null);
db.collection.ensureIndex( { location : "2dsphere" }, function (err, collection) {
collection.update({'Username':username}, {$set: geoJsonObj}, {upsert:true}, function(err,result) {
if (err)
res.send(null);
else
res.send(jsonObj);
});
});
});
});
});
Running the following code without the ensureIndex works perfectly!
Fixed it! You have to call ensureIndex on the database (not the collection), and pass the collection as the first parameter, followed by the index.

ExpressJS mongodb multiple queries

I want to take data with two collections.
How to send this data in one response?
This is my code:
//RETURN SINGLE QUERYE
exports.findById = function(req, res) {
//Get Params
var querye_id =new BSON.ObjectID(req.params.id);
var querye;
//Get Single Querye
db.collection('queryes', function(err, collection) {
collection.findOne({'_id':querye_id}, function(err, item) {
querye=item;
});
});
//Get Questions and Answers
db.collection('questions', function(err, collection) {
collection.find().toArray(function(err, items) {
querye.questions=items;
});
});
//Send Response
res.send(querye);
};
I have varible querye as undefined. How to solve this?
var async = require('async');
function getQueries(id, callback) {
db.collection('queryes', function(err, collection) {
collection.findOne({'_id':id}, callback);
});
}
function getQuestions(callback) {
db.collection('questions', function(err, collection) {
collection.find().toArray(callback);
});
}
exports.findById = function(req, res) {
var querye_id =new BSON.ObjectID(req.params.id);
async.parallel({
querye: async.apply(getQueries, query_id),
questions: getQuestions
}, function (error, results) {
if (error) {
res.status(500).send(error);
return;
}
results.querye.questions = results.questions;
res.send(results.querye);
});
};
What you should probably do is use deferreds/promises to get the results in a waterfall manner then return the results when everything is completed.
I like to use the async library for node.
https://npmjs.org/package/async
What this lets you do is queue up all of your async functions then report back success/failure. At the very end you will get the results.
Assuming you already required the async module your code would look something like this.
exports.findById = function(req, res) {
//Get Params
var querye_id =new BSON.ObjectID(req.params.id);
async.waterfall([
function(callback){
//Get Single Querye
db.collection('queryes', function(err, collection) {
collection.findOne({'_id':querye_id}, function(err, item) {
callback(null, item);
});
});
},
function(arg, callback){
//Get Questions and Answers
db.collection('questions', function(err, collection) {
collection.find().toArray(function(err, items) {
arg.questions=items;
callback(null, arg);
});
});
}],function(err, results){
//Send Response
res.send(results);
});
};

nodejs get find results in mongodb

I'm trying to get the result of query but i get the same info in all vars: db, collection and res:
var mongodb = require("mongodb");
var mongoserver = new mongodb.Server("localhost", 27017);
var instance = new mongodb.Db("test", mongoserver);
instance.open(function(err, db)
{
console.log('db:');
console.log(db);
db.collection('kurtsoa', function(err, collection)
{
console.log('collection:');
console.log(collection);
collection.find({}, function(err, res)
{
console.log('res:');
console.log(res);
});
});
});
how i can get the result of "find"?
.find() will return a Cursor object for you to work with. If all you are interested in is getting all the results in an array you can do:
collection.find().toArray(function(err, docs) {
console.log(docs);
});
But you can also iterate the cursor too:
collection.find().each(function(err, doc) {
//called once for each doc returned
});
You can use this:
collection.find().toArray(function(err, docs){
console.log(docs);
)};

Resources