简体   繁体   中英

Dynamically query a nested field in mongoDb

I want to make a query to my mongoDb with this query. I however have a challenge in making a dynamic query.

Here is a sample array for a user. The problem is that the preferences are different for each user.

 dynamicArray = [ 'sample1', 'sample2', ];

 const query = { visibility: true, $or: [ {"myField.sample1": true}, {"myField.sample2": true}, ] }; const recipes = await Recipe.find(query).countDocuments();

This works because I hardcoded the values of sample1 and sample2 from the array. I need to be able to pass sample1, and sample2 dynamically into the query based on the values in the dynamicArray without hard coding them like I did here. How can I get this done please?

You can use this script to generate objects into the array.

 const dynamicArray = [ 'sample1', 'sample2', ]; var query = {visibility: true, $or: []}; dynamicArray.map(m => { const key = "myField."+m var obj = {} obj[key] = true query.$or.push(obj)}) console.log(query)

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