Reputation: 1167
I'm sure this must be a duplicate, but I must have read a 100 questions by now, but I still haven't been able to figure this out.
I have a function that takes four aguments: senderId
, field
, content
and response
in a node module. The function itself runs a Mongoose Model Update to update the specified field with the supplied content. Code below:
module.exports = function(senderId, field, content, response) {
var errorMessage = "Sorry, I'm having problems processing your request. Please try again later.";
cemForm.update({ "senderId" : senderId }, {
field : content
}, function(err, res) {
if (err) {
console.log(err);
fb.textOnlyMessage(senderId, errorMessage);
} else {
fb.sendButtonMessage(senderId, response);
}
});
};
If I use this function like so:
cemUpdate(event.sender.id, "issueType", cemQuestions.issue.buttons[0].title, cemQuestions.voiceSpecificIssue);
The code executes perfectly and I get the correct response, however, the database is not updated. If I replace the object key field
with its contents (issueType
), the database updates appropriately. I've tried logging the variable, and I'm 100% certain that it is a string and it is issueType
.
What am I missing?
Upvotes: 0
Views: 180
Reputation: 2223
In ES6 you can use computed property keys:
module.exports = function(senderId, field, content, response) {
var errorMessage = "Sorry, I'm having problems processing your request. Please try again later.";
cemForm.update({ "senderId" : senderId }, {
[field] : content
}, function(err, res) {
if (err) {
console.log(err);
fb.textOnlyMessage(senderId, errorMessage);
} else {
fb.sendButtonMessage(senderId, response);
}
});
};
Upvotes: 1
Reputation: 659
It's because you can't reference a field using a variable. To get round it do something like....
module.exports = function(senderId, field, content, response) {
var errorMessage = "Sorry, I'm having problems processing your request. Please try again later.";
var updateObj = {};
updateobj[field] = content;
cemForm.update({ "senderId" : senderId }, updateObj, function(err, res) {
if (err) {
console.log(err);
fb.textOnlyMessage(senderId, errorMessage);
} else {
fb.sendButtonMessage(senderId, response);
}
});
};
Untested, but hopefully should work.
FYI: Here's a simple example without Mongo etc here
Upvotes: 2