简体   繁体   中英

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

I have a problem with a query on mongodb. First of all, I have this object on my mongoose schema, like this

obj_proof: {
        field1_proof: String,
        field2_proof: String 
}

I would like to make a query on mongo in which a part of a field name changes automatically(really it is passed as parameter of a function) This is an example:

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
});

But it doesn't work. The problem is that I don't want to duplicate this function , because the obj_proof is always the same. On the other hand, field changes.

Try This

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
});

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM