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
Related
Trying to iterate through a database and add the values to an array in Node.js. When I try to push the items based on their column name ('account name':res.rows[i].account_name), I get an "undefined" error.
If I push the item in with the "accountList.push(res.rows[i])" line, all the data goes into the object but it isn't labelled.
I have a feeling that this is something to do with the async nature of Node.
What am I doing wrong?
const query = {
name: "getDB",
text: "select * from smartsneakers",
rowMode:'array',
}
pool.query(query, (err,res) => {
if (err) {
res.status(500).json({"status_code": 500, "status_message": "internal server error"});
} else {
for (let i = 0; i < res.rows.length; i++) {
console.log(res.rows[i].account_name)
//accountList.push(res.rows[i]);
var account = {
'account name':res.rows[i].account_name,
}
accountList.push(account);
}
//console.log(accountList);
console.log(accountList[0]);
}
})
//close connection
pool.end();
It was because I was using "rowMode:'array'" so it was outputting the whole row.
The question led me to the answer - thanks!
Been staring at this for awhile and not sure why it is not working. I am trying to create an object within an embedded object, however, it seems like I am not passing the params down correctly as it says listings[j] is undefined. What do I need to pass into that piece for it to work?
function createBid(req, res) {
//get current listing object info
db.Listing.findById(req.params.listingId, function(err, foundListing) {
// console.log(foundListing._id );
if (err) {
console.log('Error', err);
}
res.json(foundListing);
// get array of all users
db.User.find({}, function(err, users) {
// for loop iterates through all users' listings
for (var i = 0; i < users.length; i++) {
var listings = users[i].listings
// for loop iterates through all listings ids
for (var j = 0; j < listings.length; j++) {
// finds match
// comparing _id with _id returning false. Not sure why, will return later
if (listings[j].topic === foundListing.topic && listings[j].created === foundListing.created) {
console.log("Found match: " + foundListing.topic);
// get current user id to add to bid object
db.User.findById(req.user, function(err, user) {
if (err) {
console.log(err);
}
var newBid = new db.Bid(req.body); // add data validation later
newBid.uid = user._id
// pushes new bid object into embedded listing
listings[j].bids.push(newBid);
listings[j].save(function(err, savedBid) {
console.log('newBid created: ', newBid);
res.json(newBid);
});
});
}
}
}
})
if (err) {
console.log(err);
}
});
};
I have a javascript and I'm trying to print the names of all my alarms in AWS cloudwatch, i.e. "jeisld-k-wialckei33k-High-CPU-Utilization, ajikh-q-m98k145k-High-Disk-Writes" etc.
My code:
//configure AWS region/securities
var cw = new AWS.CloudWatch();
var alarms = cw.describeAlarms();
for (var i = 0; i < alarms.length; i ++) {
console.log(alarms[i]);
However this doesn't print anything at all. Is this the correct way to get the names of all my alarms?
EDIT:
console.log(alarms) prints
[object Object]
Try this
AWS CloudWatch Docs
var cloudwatch = new AWS.CloudWatch();
cloudwatch.deleteAlarms(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else showAlarms(data); // successful response
});
function showAlarms(data){
for (var i=0; i<data.MetricAlarms.length; i++){
console.log(data.MetricAlarms[i]. AlarmName);
}
}
If that doesn't work, you can loop through the object to see how it is structured, which might give you a sense of what you are working with.
function showAlarms(data){
for (var item in data) {
console.log(item);
for (var sub in item) {
console.log('>:'sub);
}
}
}
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.
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