Reputation: 11
UPDATE : GOT IT WORKING See bottom.
I've got this little script going to make a SQL query using node.js, using a variable supplied by a user in a discord channel (upperArgs). The idea is it prints found data in console, and prints "No record" in console if the query comes up null.
Works great if the query finds a record, but if it doesn't I still get
TypeError: Cannot read property 'registered_owner' of undefined
I've tried a range of solutions like splitting the concat into two separate queries and more, but I can't seem to get this error to stop throwing.
client.on('message', async message => {
//Then ignores them if they are from another bot.
if (message.author.bot) return;
// Or if they don't have our specified prefix
if (message.content.indexOf(config.prefix) !== 0) return;
// Or if they aren't in our specified channel
if (message.channel.id === (config.channelid)) {
// Strips prefix, lowercases command, uppercases args to match db value.
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const upperArgs = args.map(arg => arg.toUpperCase());
var platequery = "SELECT CONCAT(firstname,' ', lastname) AS registered_owner FROM essentialmode.users where identifier = (Select owner FROM essentialmode.owned_vehicles where plate = '" + upperArgs + "')";
if (command === 'check') {
var tag = await con.query(platequery, function(err, result) {
if (err) throw err
if (tag !== undefined)
{
var platedata = (result[0].registered_owner);
console.log(platedata);
}
else console.log("Not found")
});
}
}
});
UPDATE : GOT IT WORKING using result.length
if (command === 'check') {
var tag = await con.query(platequery, function(err, result) {
if (err) throw err
if (result.length > 0) {
if (result)
console.log("Registerd to " + result[0].registered_owner)
}
else console.log('Stolen');
});
}
Upvotes: 1
Views: 1504
Reputation: 11
if (command === 'check') {
var tag = await con.query(platequery, function(err, result) {
if (err) throw err
if (result.length > 0) {
if (result)
console.log("Registerd to " + result[0].registered_owner)
}
else console.log('Stolen');
});
}
Upvotes: 0
Reputation: 8617
You should check if result has a [0] element before trying to access its properties, and then check if registered_owner is in result[0].
Alternatively, you could use something like lodash and do _.get(result,'[0].registered_owner',null)
if (typeof tag !== "undefined")
{
var platedata = result.length > 0
? 'registered_owner' in result[0]
? (result[0].registered_owner)
: null
: null ;
console.log(platedata);
}
Upvotes: 1