I am using mongoDB with javascript. I am updating an item in a collection using the following function and passing in "server_name" as the variable attribute_name:
async update_server_attribute(db, server_id, attribute_name, new_value){
var my_query = { "server_id": server_id }
var updated_val = { $set: {attribute_name: new_value } }
db.collection("servers").updateOne(my_query, updated_val)
},
I would expect the dict to update to the following:
{"server_name" : new_val}
Instead it does the following:
{"server_name" : old_value, "attribute_name" : new_val}
Can anyone explain this strange behavior and how to fix it?
In JavaScript, {attribute_name: new_value }
is treated the same as {"attribute_name": new_value }
. To have JavaScript use the value of attribute_name
as the key, use computed property name syntax by surrounding it with square brackets:
var updated_val = { $set: {[attribute_name]: new_value } }
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.