Get an objects value by accessing and matching it's key value - javascript

I am retrieving an object with a database call, I want to access a key's value by matching that key with a variable that I have.
In my database return I get an object that looks similar to this:
{"_id":"5c840d548a7db8af2f9eefea",
"domain":"chatbotdemo.com","deliveryTime":"ba",
"emailAddress":"ab","freeDelivery":"ab","onSale":"ab"}
I have a variable:
var intent = 'emailAddress'
The variable should always exist but theres a very slight chance it may not
and it may also be null.
What I want to do is access the value from that key field that matches the var intent, or at least get the key value pair.
What I also want to do is then if it is null then call an error, my full code is below:
getClientsDialog: function (domain, intent, callback) {
MongoClient.connect('mongodb://111011001101101', function (err, client) {
if (err) throw err;
var db = client.db('10001101');
db.collection('dialog').findOne({ domain: domain}, function (err, doc) {
// here I would want to say if (!err && ****logic to check match****)
if (!err) {
callback(doc)
} else {
throw err;
callback(err)
}
client.close();
});
console.dir("Called findOne");
});
}
Any help would be greatly appreciated!
Thanks!!

Not sure if i got the problem right but in ES6 you can use a computed value as an property name. Something like this:
let serverJson = {
"_id":"5c840d548a7db8af2f9eefea",
"domain":"chatbotdemo.com","deliveryTime":"ba",
"emailAddress":"ab","freeDelivery":"ab","onSale":"ab"
};
let intent = "emailAddress";
if (serverJson[intent]!== undefined) {
}
else {
}

Related

Querying MySQL with JS Object returning [object Object] as table name

I'm building a program that queries MySQL databases, gets the tables, fields, field data types, and entries and returns it as a single object to be later used to view the MySQL data as a table.
This is what the built object will look like:
{
`Table_Name`: {
Title: `Table_Name`,
Fields: {
`Field Name`: `Datatype`
},
RowData: []
}
}
The query to get the tables is fine, however the query to get the row data isn't. The query function looks like this:
function getRows(){
let secondpromises = [];
secondpromises.push(
new Promise((resolve, reject) => {
for(x in Tables){
Connect_SQL(SQLcreds, w_newSconn, (conn) => {
conn.query(`SELECT * FROM ${Tables[x]}`, (err, results) => {
if(err){
console.log(err);
reject(err);
}else{
for(r in results){
Tables[`${Tables[x].Title}`].RowData.push(results[r]);
}
resolve(results);
}
});
});
if(x == Tables.length - 1){
Promise.all(secondpromises).then(() => {
if(w_newSconn){
w_newSconn.close();
w_newSconn = null;
}
console.log(Tables);
});
}
}
})
);
}
The error is coming from conn.query(). It is throwing an error stating there is an error in my SQL syntax at:
SELECT * FROM [object Object]
I understand the reason why and I'm sure there is a way to resolve this through JSON.Stringify() but there must be a simpler way. I have already tried creating a variable like so:
let objArray = Object.keys(Tables)
But it still returned [object Object], any help would be appreciated.
Tables[x] is an object. You need to get the table name from it.
conn.query(`SELECT * FROM ${Tables[x].Title}`, (err, results) => {
It also looks like the property name is the same as the title, so you can do:
conn.query(`SELECT * FROM ${x}`, (err, results) => {
I ended up creating a variable in the loop
let table = keys[x]
and that did the trick, for whatever reason ${keys[x]} was returning undefined but the variable returned the table name. Theoretically I could have changed the for loops to a
for(x in Tables)
and x would have returned the title so I may go back and rewrite it that way. Thank you.

Cannot set property 'employeeNum' of undefined

I am writing a function that is meant to add an employee to the end of a list of employees, but I continue to be met with the error in the title. I've tried to alter the code, but I'm not sure what I'm doing wrong. Here's the function:
data-service.js
module.exports.addEmployee = function(employeeData) {
employeeData.employeeNum = ++empCount;
return new Promise(function(resolve,reject) {
employees.push(employeeData);
if(employees.length == 0) {
reject("no results returned");
}
resolve(employeeData);
});
}
server.js
app.get("/employees/add", (req,res) => {
res.render("addEmployee");
});
app.post("/employees/add", (req, res) => {
console.log(req.body);
res.redirect("/employees");
});
The current function is not the root of the problem... However, you are trying to set a property on a param that you expect to be an object. But the caller has either passed a variable that has a value === undefined, or perhaps is passing no params at all ( either way, the param employeeData is undefined and you have no checks against it, thus we see the error).

How to return a nodejs callback as a number, from a JSON object property value?

I am trying to do maths on a number within a JSON object (the price of a stock ticker).
I want it to be a variable called 'btcusd_price', that I can then use to do arithmetic with.
How do I get a variable i can work with?
https://tonicdev.com/npm/bitfinex
var Bitfinex = require('bitfinex');
var bitfinex = new Bitfinex('your_key', 'your_secret');
var btcusd_price;
btcusd_price = bitfinex.ticker("btcusd", function(err, data) {
if(err) {
console.log('Error');
return;
}
console.log(data.last_price);
return data.last_price;
});
typeof btcusd_price;
console.log(btcusd_price); //i'm trying to work with the price, but it seems to be 'undefined'?
You have to set the values when they are available, the code is async and you were using the value before it is applied to btcusd_price. Note that the proper way to use the variable is when the callback executes its code.
Please, see the working code below:
Bitfinex = require('bitfinex');
var bitfinex = new Bitfinex('your_key', 'your_secret');
var btcusd_price;
bitfinex.ticker("btcusd", function(err, data) {
if(err) {
console.log('Error');
return;
}
btcusd_price = data.last_price;
console.log(typeof btcusd_price);
console.log(btcusd_price);
});

Mongoose won't update a document

I'm encountering few problems when dealing with mongoose.
I wrote the following snippet of code:
if (!usr.settings) usr.settings = {};
async.forEach(Object.keys(params), function (item, nextitem){
usr.settings[item] = params[item];
nextitem();
}, function (err) {
if (err) return callback(err);
usr.save(function(err) {
if (err) return callback(err);
return callback();
});
});
When I first use it, it works just fine, it creates all the items in the document perfectly, but when I use it the 2nd time (lets say I want to update those items) it doesn't change their values nor gives me any error.
The data stays just the same.
I tried to debug it.
if (!usr.settings) usr.settings = {};
async.forEach(Object.keys(params), function (item, nextitem){
usr.settings[item] = params[item];
nextitem();
}, function (err) {
if (err) return callback(err);
usr.save(function(err) {
console.log(usr); <------------------- [At this point it shows the updated data but for some reason it doesnt save it to the db]
if (err) return callback(err);
return callback();
});
});
Any idea why it could happen?
Thanks.
After messing with it, found the solution.
lets say you are using the following schema:
user_schema = {
settings = Object
}
you won't be able to set setting., therefore the following code:
usr.settings.something = 123;
usr.save(function(err) {
if (err) return callback(err);
return callback();
});
will do nothing and still will not result in an error.
If you want to fix the issue, apply this fix to the schema:
user_schema = {
settings = {
something : Number
something_else: Object
}
}
now you will be able to set something with a value :)
I wish it would helpful to someone

Getting an object from MongoDB using its id

Let me explain my problem first.
I am trying to get the ID from URL and use it to find a record in the database(MongoDB). The following code I have in NodeJS Express App.
app.post('/dashboard/profile/update/:id',function(req,res){
var to_update=req.params.id;
var firstName=req.body.fname;
obj_to_search={_id:to_update};
db.open(function(err, dbs) {
if(!err) {
dbs.collection('project',function(err, collection) {
//update
collection.findOne(obj_to_search, function(err, result) {
if (err) {
throw err;
} else {
res.send(result);
}
dbs.close();
});
});
}
});
});
I am getting the record if I hard code the ID to 1. But I am not getting the record by this way. However I have checked using console.log the ID i am getting through URL is also 1.
Convert strings to integers
If a variable is in the url - it's a string. If you're wanting to query the database with a number, you'll need to cast it to a number for use in the query:
obj_to_search={_id: parseInt(to_update,10)};

Categories