MongoDB:$根据变量的内容推入数组 [英] MongoDB: $push into an array based on a variable's contents
本文介绍了MongoDB:$根据变量的内容推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将$push
一个项目放入MongoDB
构建在Node
上的MongoDB
中的记录中(使用MongoJS
),就像这样:
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);
}
});
};
这行得通,除了函数将"param:bar"而不是"foo:bar"推送到我的记录中(有关此内容,请参见上面的评论).
This works, except the function is pushing "param: bar" instead of "foo: bar" to my record (see comments above for what this refers to).
我尝试做$push: {eval(param):value}
,这在黑暗中有点枪响,但还是无法正常工作.做到这一点的最佳方法是什么?
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..
});
这篇关于MongoDB:$根据变量的内容推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文