MongoDB: $push into an array based on a variable's contents

老子叫甜甜 提交于 2019-12-11 13:59:50

问题


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:


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

db.users.update({"_id": ObjectId(user)}, { $push: ob }, function (err, record) {
    // etc..
});


来源:https://stackoverflow.com/questions/17788220/mongodb-push-into-an-array-based-on-a-variables-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!