1

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?

1 Answer 1

2
var ob = {};
ob[param] = value;

db.users.update({"_id": ObjectId(user)}, { $push: ob }, function (err, record) {
    // etc..
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.