我有一个node.js api,用户可以在其中将所需字段作为数组发送,以便从mongodb 数据库中获取。我需要使用查找查询查找该字段的数据。我编写了 forEach 语句来循环该数组并获取数组元素。但是,当我尝试通过在查询中插入数组元素来获取结果时,它没有给出所需的结果。任何人都可以通过查看下面的代码来帮助我解决问题吗?
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";
}
预期输出是,
[ { humidity: 36 } ]
但我只得到 _id
之类的,
[ { _id: 5dce3a2df89ab63ee4d95495 } ]
我认为data
不适用于查询。但我在控制台中打印数据,通过显示湿度等数组元素来给出正确的结果。我需要做什么才能使其正常工作?
最佳答案
当您传递 {data: 1} 时,您正在传递一个数组,其中需要列名称。 您必须创建一个对象,其中键将是数组的元素并将它们设置为 1。
const projection = data.reduce((a,b) => (a[b]=1, a), {});
[...] .find({}, projection) [...]
关于node.js - 如何使用 mongoose 在 mongodb 中搜索具有动态字段的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59053010/