javascript - mongodb express.js 在数组中查找对象
问题描述
我有这个看起来像这样的数据库“equipos”:
[
"_id" : ObjectId("5ae4ea9f434d9b51dad68813"),
"team_name" : "Alavés",
"nombre_equipo_movil" : "ALA",
"cantidad_integrantes" : 20,
"partidos_jugados" : 29,
"partidos_ganados" : 10,
"partidos_empatados" : 1,
"partidos_perdidos" : 18,
"goles_a_favor" : 26,
"goles_en_contra" : 45,
"players" : [
{
"dorsal" : 1,
"nombre_jugador" : "Fernando Pacheco",
"edad" : 25,
"nacionalidad" : "España",
"posicion" : "Portero",
"goles" : 0,
"asistencias" : 0,
"amarillas" : 4,
"rojas" : 1
}
...
]
...
]
所以我想检查 Alavés 队中是否有“背”为 1 的球员,我正在这样做
db.equipos.findOne({"team_name": "Alavés" }, {"players": {$elemMatch: {"dorsal": 1l}}})
问题是当没有背 1 的玩家时对该查询的响应是:
{ "_id" : ObjectId("5ae4ea9f434d9b51dad68813") }
那是团队的ID。问题是,当我使用 express 发送该查询时,例如:
dbo.collection("equipos").findOne(
{"team_name": sReq.body.nombre_equipo }, {"players": {$elemMatch: {"dorsal": sReq.body.dorsal}}},
function(err, res){
我无法将 res 与 null 进行比较,以查看它是否找不到具有该背部的球员,因为我总是得到球队的 ID...
那么如何使用该响应检查该播放器是否不存在?
解决方案
不要res
与比较null
,您可以Object.keys(res).length == 1
针对这种情况进行比较。我真的不知道你的查询为什么会产生这个结果。但我认为这会对你有所帮助。
if(Object.keys(res).length == 1) {
console.log("No player found!");
} else {
console.log("Hey there!");
}
推荐阅读
- sql - 在 Azure CosmosDB 中查找字段的不同值
- python - 在discord.py中制作机器人,如何按行会分隔用户数据?
- c++ - 为什么不调用临时 ojbect 构造函数?
- javascript - react native/react中的过滤和映射
- symfony - Symfony - 通过引用访问表单名称
- ssh - Windows 10 - 如何让 ssh 与 ssh-agent 通信
- blazor - Blazor WASM - 如何在布局内更改正文类动态
- vba - 如何使用 InternetExplorer.Application 对象在 VBA 中打开 HTMLDocument 对象
- javascript - 如何让 Google 脚本在特定行的特定范围内隐藏特定列中带有空格或零的行?
- html - 如何在Angular中检查长度