将变量用作mongodb中字段名的一部分

Using variable like a part of a field name in mongo db?

本文关键字:字段 一部分 mongodb 变量      更新时间:2023-09-26

我在mongodb上的查询有问题。首先,我在猫鼬模式中有这个对象,比如这个

obj_proof: {
        field1_proof: String,
        field2_proof: String 
}

我想对mongo进行一个查询,其中字段名的一部分会自动更改(实际上它是作为函数的参数传递的)这是一个例子:

var attr = 'obj_proof.'+field; //field is passed by the some function in which                there is this code
    ProofSchema.update({ 'Id': Id }, { attr : value }, function(err, result) {  //Id is another parameter that is passed by the same function, like field and value
});

但它不起作用。问题是我不想重复这个函数,因为obj_prof总是一样的。另一方面,字段发生变化。

试试这个

var attr = 'obj_proof.' + field; //field is passed by the some function in which                there is this code
var key_attr = {};
key_attr[attr] = value; // the value

ProofSchema.update({'Id': Id}, key_attr, function(err, result) {  //Id is another parameter that is passed by the same function, like field and value
});

感谢