简体   繁体   中英

How to make monk findoneandupdate property a variable?

I'm trying to find and update a field in a document using Monk. The problem is, I am trying to using a variable in the property area. (property: value) The type, and the value.

let result = await collection.findOneAndUpdate({type: value}, { $set: { blacklisted: false} })

When I set type to for example, apple with let type = "apple" it does not use the type variable in findOneAndUpdate.

Where as if I just put apple in like this

let result = await collection.findOneAndUpdate({"apple": value}, { $set: { blacklisted: false} })

It worked 100% fine.

I have tried making this an object too, like this: let obj = {type, value} then putting that into the find and update let result = await collection.findOneAndUpdate(obj, { $set: { blacklisted: false} })

Yet, still no luck. Any help? Thanks.

In order to use the value of a variable as a key, you should use brackets []

let type = "apple"
let result = await collection.findOneAndUpdate(
  { [type]: value },  <----- Using [] on type variable 
  { $set: { blacklisted: false } }
);

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