문제

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?

도움이 되었습니까?

해결책

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

db.users.update({"_id": ObjectId(user)}, { $push: ob }, function (err, record) {
    // etc..
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top