I have the following code...
var tagMap = {};
console.log("Data" + data);
console.log(JSON.stringify(data));
for(var item in data.results){
tagMap[item.path.key] = item.value.name;
}
But it outputs...
Data[object Object]
{ "count":1,
"total_count":1,
"results":[
{"path": {"collection":"ProcessedReports","key":"20140225.DIF","ref":"4802caab51897eae"},"value": {"name":"20140225.DIF"},"score":1}
]
}
undefined
project/routes/index.js:73
for(var item in data.results){
^
TypeError: Cannot read property 'results' of undefined
I am confused, how is it getting set back to null?
Update
Thanks to a comment I noticed the log was actually the following...
Data[object Object]
{"count":1,"total_count":1,"results":[{"path":{"collection":"ProcessedReports","key":"20140225.DIF","ref":"4802caab51897eae"},"value":{"name":"20140225.DIF"},"score":1}]}
Dataundefined
undefined
this leads me to believe the method is getting called 2x I will try to add more code asap.
Full route (expressjs) using orchestrate.io, still can't find the dual call. Only 1 call to getloadedfiles I can find so far in the source.
exports.getloadedfiles = function(req, res, next){
miao.search({
collection: 'ProcessedReports',
query: '*'
},
function (err, data) {
var tagMap = {};
console.log("Data" + data);
console.log(JSON.stringify(data));
for(var item in data.results){
tagMap[item.path.key] = item.value.name;
}
req.processed = tagMap;
return next();
});
}
With the grep of my project...
grep -r getloadedfiles ./
.//app.js:app.get('/files/list', routes.getloadedfiles, routes.getfiles, routes.renderfiles);
.//routes/index.js:exports.getloadedfiles = function(req, res, next){
It should probably be
for(var item in data.results){
tagMap[ data.results[item].path.key ] = data.results[item].value.name;
}
accessing the objects values with the key passed in the loop, otherwise you're doing
0.path.key
as in trying to access properties on the string that is the key, which won't work
FIDDLE
Another thing, data.results is an array, and should be iterated with
for (var i=0; i<data.results.length; i++) { ...
And then you'd end up with
for (var i=0; i<data.results.length; i++) {
tagMap[data.results[i].path.key] = data.results[i].value.name;
}
FIDDLE
Related
I am using redis list for storing the value for a key in nodeJS. I have made the following function and exported it to another file to make it a api:
async function set(id, ...seats) {
var seatArr = [];
for(var i = 0; i < seats.length; i++)
{
seatArr = seatArr.concat(seats[i]);
}
try{
result = await client.rpush('seats_'+id, ...seatArr);
} catch(err) {
console.log(err)
}
}
module.exports = {
set : set()
};
But I am getting the following error:
{ ReplyError: ERR wrong number of arguments for 'rpush' command
at parseError (/home/shivank/Music/node-app/ticket-booking/node_modules/redis-parser/lib/parser.js:179:12)
at parseType (/home/shivank/Music/node-app/ticket-booking/node_modules/redis-parser/lib/parser.js:302:14) command: 'RPUSH', args: [ 'seats_undefined' ], code: 'ERR' }
Please help me to resolve this.
Problem
You are not exproting a function, you are trying to export the result of the function (which files because you didn't provide the params that it needs).
module.exports = {
set : set(). // <<<---- You are executing the function
};
but you didn't give it any params so the id param is equal to undefined.
From your stacktrace:
..[ 'seats_undefined' ].. // 'seats_'+id === 'seats_'+`undefined` === 'seats_undefined'
Solution
module.exports = {
set : set
};
I am trying to send an object from nodejs server to the front end but one property is keep getting deleted on the way
server
router.post('/cart/retrieve', (req, res) => {
let cart = req.session.cart;
let prodId = Object.keys(cart);
Product.find({_id: {$in: prodId}}, (err, result) => {
if (err) throw err;
let resultToSend = [];
for (let i = 0; i < result.length; i++) {
let curResult = result[i];
curResult['cartQuantity'] = parseInt(cart[curResult._id]);
result[i] = curResult;
}
resultToSend = result;
console.log(resultToSend[0]['cartQuantity'])
res.json({cart: resultToSend})
});
});
frontend
$("#top-cart-trigger").click(function(e){
$.post('/api/shop/cart/retrieve',{
}, function (returnResult) {
console.log(returnResult['cart'][0]['cartQuantity'])
let products = returnResult['cart'];
console.log(returnResult)
for(let i = 0; i < products.length; i ++){
let curProduct = products[i];
console.log(curProduct['cartQuantity'])
}
});
});
so practically the json variable sent from server and the returnResult received from the front end are same variables. However, my console.log(resultToSend[0]['cartQuantity']) returns 3 (which is correct) but console.log(curProduct['cartQuantity']) is undefined for all elements. What am I doing wrong?
I think the problem might comes from mutable variable result in your server.
However it seems like the variable returnResult['cart'] is JSON and you are expecting array. You could use 'for in' instead. See https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Statements/for...in
Just try to replace for loop with this
for (let key in returnResult['cart']){
console.log(returnResult['cart'][key]['cartQuantity']);
}
I'm having trouble getting the following to work
var data = db.collection('mycollection', function(er, collection) {
return collection.find().toArray();
});
The resulting data is not an array. I don't get what's wrong. How do I set a varaible to the contents of find().toArray()?
I've tried logging the contents like this so I know that there must be data:
db.collection('mycollection', function(er, collection) {
collection.find().toArray(function(err, results) {
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
}
});
});
Thanks! I'm very new to ajax programming and mongodb.
Just go it like in simple way:-
.find method always provide data in array format.
var query = db.collection.find({},function(err,data){
if(err) throw err;
console.log(data); // give in array.
})
thanks
I am working in node.js.
I make a rest api call in .js file as follows:
$http.get("/api/products/"+cat_id).success(
function(response){
//$scope.cat_id = response;
console.log("Got response products for page 1");
console.log("Received products for cat :"+response.pdt.cat_id);
}
)
The following code snippet is contained in a file app.js:
app.get('/api/products/:cat', function(req, res){
var pdts = [];
for(var i=0; i<=6; i++){
var pdt = {
id : "1" + i
, name: 'Product' + i
,cat_id: req.params.cat
};
pdts.push(pdt);
}
res.json(pdts);
});
The array of objects pdts is sent as a response through the last statement.
Now how do I access the individual attributes of my object pdt??
The result of
console.log("Received products for cat :"+response.pdt.cat_id);
is
Cannot read property 'cat_id' of undefined
You are returning an array of objects, so you need to loop through it and access each element individually:
$http.get("/api/products/" + cat_id).success(function(response) {
console.log("Got response products for page 1");
// response is an array of javascript objects
for (var i = 0; i < response.length; i++) {
var element = response[i];
console.log("Received products for cat :" + element.cat_id);
}
});
or if you wanted to access some element directly by index:
console.log("Received products for cat :" + response[0].cat_id);
Obviously it is recommended that you first check the size of the array to ensure that the element you are trying to access exists.
In my Express route, I am trying to return a list of elements that I am grabbing from MongoDB using Mongoose. I'm basically iterating through an array of items, and making MongoDB calls to get the parameter objects that each item has. However, I'm having trouble making sure that I get all the parameters before I send the response. I've tried using promises, other async library functions, etc, but none of them have seemed to work.
The current iteration of the code looks like this (I have tried a lot of different things):
exports.findAll = function(req, res){
Flow.find({}, function(err, items) {
console.log(items);
var payload = {}
var params = [];
for (var i=0; i < items.length; i++) {
var count2 = 0;
async.whilst(
function() {
return ((items[i]) && (count2 < items[i].params.length));
},
function(callback) {
Parameter.findById(items[i].params[count2], function(err, out) {
params.push(out);
count2++;
callback();
});
},
function(err) {
console.log(params);
var payload = {
"flows": items,
"params": params
};
res.send(payload);
console.log('success: flows found');
}
);
}
This code sends a payload with params not being completely full.
What would be a good way to deal with this? Honestly I just want these database calls to be synchronous, but I just can't figure out how to make this work.
This doesn't really seem necessary as you can actually use the $in operator with all the results from your first query:
Flow.find({},function(err,items) {
var ids = [];
// blocking? yes, but should be minor - do better if there are problems
for ( var i=0; i < items.length; i++ ) {
for ( var n=0; n < items[i].params.length; n++ ) {
ids.push( items[i].params[n] );
}
}
Parameter.find({ "_id": { "$in": ids } },function(err,params) {
res.send({ "flows": items, "params": params });
});
});
So there should be no reason to execute multiple queries inside an async loop, or loops as your code seems to be missing as the direct cause of the problem there.