AWS Cloudwatch get names of alarms - javascript

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);
}
}
}

Related

Undefined errors using Node.js, Mongoose, and Discord.js [Cannot read property of undefined]

I've been scouring similar problems but haven't seem to have found a solution that quite works on my end. So I'm working on a Discord bot that takes data from a MongoDB database and displays said data in the form of a discord embedded message using Mongoose. For the most part, everything is working fine, however one little section of my code is giving me trouble.
So I need to import an array of both all available users and the "time" data of each of those users. Here is the block of code I use to import said data:
for (i = 0;i < totalObj; i++){
timeArray[i] = await getData('time', i);
userArray[i] = await getData('user', i);
}
Now this for loop references a function I made called getData which obtains the data from MongoDB by this method:
async function getData(field, value){
var data;
await stats.find({}, function(err, result){
if(err){
result.send(err);
}else{
data = result[value];
}
});
if(field == "user"){
return data.user;
}else if (field == "time"){
return data.time;
}else{
return 0;
}
So that for loop is where my errors currently lie. When I try to run this code and display my data through a discord message, I get this error and the message does not get sent:
(node:13936) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'time' of undefined
Now the strange thing is, this error does not happen every time. If I continue calling the command that triggers this code from my discord server, it's almost like a 50/50 shot if the command actually shows the message or instead gives this error. It is very inconsistent.
This error is confounding me, as the undefined part does not make sense to me. The objects that are being searched for in the mongoDB collection are definitely defined, and the for loop never exceeds the number of objects present. My only conclusion is that I'm doing something wrong with my asynchronous function design. I have tried altering code to use the getData function less often, or to not use awaits or asynchronous design at all, however this leaves my final discord message with several undefined variables and an eventual crash.
If anyone has any advice or suggestions, that would be very much appreciated. Just for reference, here is the full function that receives the data, sorts it, and prepares a string to be displayed on the discord server (though the error only seems to occur in the first for loop):
async function buildString(){
var string = "";
var totalObj;
var timeArray = [];
var userArray = [];
var stopSort = false;
await stats.find({}, function(err, result){
if(err){
result.send(err);
}else{
totalObj = result.length;
}
});
for (i = 0;i < totalObj; i++){
timeArray[i] = await getData('time', i);
userArray[i] = await getData('user', i);
}
while(!stopSort){
var keepSorting = false;
for(i = 0; i < totalObj ; i++){
var target = await convertTime(timeArray[i]);
for(j = i + 1 ; j < totalObj ; j++){
var comparison = await convertTime(timeArray[j]);
if(target > comparison){
//Switch target time with comparison time so that the lower time is up front
var temp = timeArray[i];
timeArray[i] = timeArray[j];
timeArray[j] = temp;
//Then switch the users around so that the user always corresponds with their time
var userTemp = userArray[i];
userArray[i] = userArray[j];
userArray[j] = userTemp;
//The loop will continue if even a single switch is made
keepSorting = true;
}
}
}
if(!keepSorting){
stopSort = true;
}
}
//String building starts here
var placeArray = [':first_place: **1st', ':second_place: **2nd', ':third_place: **3rd', '**4th', '**5th', '**6th', '**7th', '**8th', '**9th', '**10th'];
for(i = 0; i < totalObj; i++){
string = await string.concat(placeArray[i] + ": " + userArray[i] + "** - " + timeArray[i] + " \n\n");
console.log('butt');
}
console.log("This String:" + string);
return string;
}
I think problem is you are trying to await function with callback, it will not work => access to data.time may run before data = result[value]. If you need await callback, you can use custom Promise (or use util.promisify, more info here)
Promise:
function findStats(options) {
return new Promise((resolve, reject) => {
return stats.find(options, function (err, result) {
if (err) {
return reject(err)
}
return resolve(result)
})
})
}
utils.promisify
const util = require('util');
const findStats = util.promisify(stats.find);
Now you can use await in your function
async function getData(field, value) {
try {
const result = await findStats({})
const data = result.value
if (field === 'user') {
return data.user
}
if (field === 'time') {
return data.time
}
return 0
} catch (error) {
// here process error the way you like
// or remove try-catch block and sanitize error in your wrap function
}
}

I am trying to parse an array of string in Jade but always results in 404

I have been trying to parse an array of strings on my jade file but it doesn't seem to work.
I can console log the array of strings from my mongodb collection but it does not reflect on my jade.
my code: from js
(global variable) let secretstitle = [];
dbo.collection("users1").findOne({secretdocument:"rousbepistola"} ,function(err, data){
if (err) throw err;
ssn.secretpost = data.secretpost;
ssn.secrettitle = data.title;
console.log(data.secretpost);
console.log(data.title)
console.log(ssn.secretpost[0]);
console.log(data.title[0])
for(let i = 0; i < (data.secretpost).length; i++) {
secretstitle.push(data.secretpost[i])
}
console.log(secretstitle);
console.log('Yay!')
db.close();
my code: from jade
.row
each n in secretstitle;
.jumbotron.col-md-12
h1 #{n}
|
h6 January 24, 2019 08:54:05 #username
|
p
| W3Schools is optimized for learning
I am trying to create a blog type content that adds to itself indefinitely like Facebook, 9gag, or twitter. I have received the console.log("yay") on my terminal. I appreciate every help I could get. By the way, my collection looks like this:
id:ObjectId("random")
secretposts:Array
0:"post1"
1:"post 2"
3:"post 3"
title:Array
0:"title 1"
1:"Title 2"
3:"Title 3"
Somewhere in the callback from your mongodb findOne call you need to add a res.render:
dbo.collection("users1").findOne({secretdocument:"rousbepistola"} ,function(err, data){
res.render('viewname', data);
});
Without that the pug/jade engine won't call the template with the returned data.
was just able to solve it now with my jade code as follow
.row
- for (var i = 0; i < himitsupost.length; ++i) {
return
.jumbotron.col-md-12(style='background-color:lightgreen;')
h3 #{himitsutitle[i]}
h5 #{himitsupost[i]}
- }
And my js file as follows
dbo.collection("users1").findOne({secretdocument:"rousbepistola"} ,function(err, data){
if (err) throw err;
ssn.secretpost = data.secretpost;
ssn.secrettitle = data.title;
console.log(data.secretpost);
console.log(data.title)
// console.log(ssn.secretpost[0]);
// console.log(data.title[0])
secretspost = [];
for(let i = 0; i < (data.secretpost).length; i++) {
secretspost.push(data.secretpost[i])
}
secretstitle = [];
for(let i = 0; i < (data.title).length; i++) {
secretstitle.push(data.title[i])
}
console.log(secretspost);
console.log('Yay!')
db.close();
});
});
res.render('release',{username:ssn.username, himitsutitle:secretstitle, himitsupost:secretspost});

Mongoose function shows variable as undefined?

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);
}
});
};

nodejs express sent object not synchronized with front end

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']);
}

Mongodb set variable to find().toarray()

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

Categories