首页 > 解决方案 > 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...

那么如何使用该响应检查该播放器是否不存在?

标签: javascriptmongodbexpress

解决方案


不要res与比较null,您可以Object.keys(res).length == 1针对这种情况进行比较。我真的不知道你的查询为什么会产生这个结果。但我认为这会对你有所帮助。

if(Object.keys(res).length == 1) {
    console.log("No player found!");
} else {
    console.log("Hey there!");
}

推荐阅读