var ob = {};
ob[param] = value;
db.users.update({"_id": ObjectId(user)}, { $push: ob }, function (err, record) {
// etc..
});
MongoDB: $push into an array based on a variable's contents
-
03-06-2022 - |
Question
I'm trying to $push
an item into my record in MongoDB
built on Node
(using MongoJS
), like so:
exports.saveToUser = function (req, res) {
console.log("IN");
var user = req.params.user;
var param = req.params.param; // equals "foo"
var value = req.params.value; // equals "bar"
console.log("Saving Data to User");
console.log(util.inspect(param, false, null));
db.users.update({"_id": ObjectId(user)}, {$push: {param:value}}, function (err, record) {
if (err) {
console.log("Lookup Error: " + err);
} else{
console.log("Updated " + user + " with " + param);
}
});
};
This works, except the function is pushing "param: bar" instead of "foo: bar" to my record (see comments above for what this refers to).
I've tried doing $push: {eval(param):value}
which was a bit of a shot in the dark but didn't work anyway. What's the best way to make this happen?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow