所以我想验证值是否在集合内。我已经使用 .map 做到了。我的代码如下所示(该字段是嵌套字段):
const loopFields = [
"nested.field1",
"nested.field2",
"nested.field3",
"nested.field4"
];
async function getField() {
const field = loopFields.map(async (fld, idx) => {
const result = await Field.findOne({ [fld]: req.body.field });
if (result) {
return fld;
}
});
const isFound = await Promise.all(field);
for (i = 0; i < loopFields.length; i++) {
if (isFound[i] !== undefined) {
return true;
}
}
}
const isValid = await getField();
if (!isValid) {
return res.status(400).send("Field not found");
}
该代码确实有效,但是我正在寻找一种重构它的方法。
答案 0 :(得分:0)
动态构建$or
子句,并将其传递给find方法,如下所示:
var loopFields = [
"nested.field1",
"nested.field2",
"nested.field3",
"nested.field4"
];
var fields = loopFields.map(field => {
var x = {};
x[field] = req.body.field;
return x;
})
db.collection.find({ $or: fields });