简体   繁体   中英

How to search data in mongodb with dynamic fields using mongoose?

I've a node.js api in which user sends the required fields as an array to be fetched from the mongodb database. I need to find the data of that fields using Find query. I've written forEach statement to loop through that array and got the array elements. But when I try to get the results by inserting the array elements in the query, it doesn't giving the required results. Could any one please help me in resolving the issue by seeing the code below?

templateLevelGraphData: async function(tid,payload){
    let err, templateData, respData = [], test, currentValue;
    [err,templateData] = await to(Template.findById(tid));
    var templateId = templateData.templateId;

    payload.variables.forEach(async data=>{
           console.log(data); //data has the array elements like variables=["humidity"]
           [err, currentValue] = await to(mongoose.connection.db.collection(templateId).find({},{data:1}).sort({"entryDayTime":-1}).limit(1).toArray());
           console.log(currentValue);
    });
    return "success";
}

The expected output is,

[ { humidity: 36 } ]

But I'm getting only _id like,

 [ { _id: 5dce3a2df89ab63ee4d95495 } ]

I think data is not applying in the query. But I'm printing the data in the console where it's giving the correct results by displaying the array elements like, humidity . What I need to do to make it work?

When you are passing {data: 1} you are passing an array where is expecting name of column. You have to create an object where the keys are going to be the elements of the array and set them to 1.

const projection = data.reduce((a,b) => (a[b]=1, a), {});
[...]   .find({}, projection)     [...]

Actually I got the solution.

for(let i=0;i<payload.variables.length;i++){
     var test = '{"'+ payload.variables[i] +'":1,"_id":0}';
     var query = JSON.parse(test);            
     [err, currentValue] = await to(mongoose.connection.db.collection(templateId).find({"deviceId":deviceId},query).sort({"entryDayTime":-1}).limit(1).toArray());
     console.log(currentValue);  //It's giving the solution
     } 

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