Mongoose添加嵌套字段过滤条件后find查询返回空数组无法向前端传数据
问题根因
你使用的{ information: { primaryType: "Grass" } }是MongoDB的全量对象匹配语法,只有当information字段下的所有子字段和你传入的对象完全一致时才会命中数据,自然无法返回符合要求的结果。查询嵌套字段的指定属性需要使用点语法标识字段路径。
正确查询写法(数据库层过滤,性能最优)
// GET request for pokedex page app.get("/pokedex", function (req, res) { // 嵌套字段路径加引号,用.连接层级 Pokemon.find({ "information.primaryType": "Grass" }, function (err, pokemon) { if (err) { console.log(err); } else { console.log(pokemon); res.render("pokedex", { pokemon: pokemon }); } }); });
替代方案:应用层JS过滤(适合复杂自定义逻辑)
如果有更复杂的过滤规则,也可以先查询全量数据,再用JS数组方法做过滤:
app.get("/pokedex", function (req, res) { Pokemon.find(function (err, allPokemon) { if (err) { console.log(err); return res.status(500).end(); } // 数组filter方法过滤符合条件的数据 const targetPokemon = allPokemon.filter(item => item.information.primaryType === "Grass"); res.render("pokedex", { pokemon: targetPokemon }); }); });
两种方案按需选择即可,数据量大时优先选择数据库层过滤方案。
内容的提问来源于stack exchange,提问作者Rednirug
相关产品推荐
相关产品推荐

