Save the date! Join us on October 16 for our Product Ops launch event. Register here.
May 18, 2019 03:14 AM
I am having an issue updating a record using the API where the update method is treating a variable as a literal value, rather than the value it contains.
My code is:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var Airtable = require('airtable');
var base = new Airtable({apiKey: 'censored'}).base('appYYigSAYG6wvbIL');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/update',function(req,res){
var exam=req.body.exam;
var status=req.body.status;
console.log(status);
console.log(exam);
res.end("yes");
base('Staff').update("recL2tsSb73D8NdVj", {
exam : status
}, function(err, record) {
if (err) {
console.error(err);
return;
}
console.log(record.get('Name'));
});
});
app.get('/', function (req, res) {
res.send('atapi is up');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
The status is read as its value (ie Pass), but exam is read as the literal word exam, causing it to fail due to that field name not existing. Can anyone point out where I am going wrong?
Solved! Go to Solution.
May 18, 2019 10:17 AM
@Justin_Barrett is on the right track. To use the vale of the variable in your object key, just need to enclose with brackets. So
{ [exam]: status }
May 18, 2019 05:56 AM
I’m just now digging back into JavaScript after a really long hiatus, but from what I understand about objects, you can’t use a variable as a name in a name:value pair. exam
in the context of exam : status
will always be treated as exam
, not as the value you assigned to the variable exam
earlier in the code. To do what you want, where the code updates a field based on the variable exam,
will require a condition, probably switch
because it’s more efficient.
May 18, 2019 10:17 AM
@Justin_Barrett is on the right track. To use the vale of the variable in your object key, just need to enclose with brackets. So
{ [exam]: status }
May 18, 2019 02:09 PM
I figured there had to be a way to still use the variable, but haven’t come to that yet in my JavaScript refresher review. :slightly_smiling_face:
May 21, 2019 05:28 AM
Thank you, this solved the issue.