简体   繁体   中英

mongodb express.js find object in array

I have this database "equipos" that looks like this:

    [   
    "_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
            }
            ...
            ]
    ... 
    ]

So I want to check if there is a player with "dorsal" 1 in the team Alavés, and I'm doing this

db.equipos.findOne({"team_name": "Alavés" }, {"players": {$elemMatch: {"dorsal": 1l}}})

the problem is that the response to that query when there is no player with dorsal 1 is:

{ "_id" : ObjectId("5ae4ea9f434d9b51dad68813") }

that being the id of the team. The problem is that when I'm sending that query with express like:

    dbo.collection("equipos").findOne(
        {"team_name": sReq.body.nombre_equipo }, {"players": {$elemMatch: {"dorsal": sReq.body.dorsal}}},
        function(err, res){

I cannot compare res to null to see if it couldn't find the player with that dorsal because I always get the ID of the team...

So how can I check that that player does not exist using that response?

Don't compare res with null , you can compare Object.keys(res).length == 1 for this situation. I really don't know why your query make that result. But I think this will help you.

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

Mongoose findOne method receives an optional second argument with the fields you want to select.

You should query like this:

dbo.collection("equipos").findOne(
        {"team_name": sReq.body.nombre_equipo,
         "players": {$elemMatch: {"dorsal": sReq.body.dorsal}}
        }, function(err, res){

Notice both fields you want to query you pass as the first argument, and the second argument will be the callback, because you don't tell mongoose which fields to select in this case.

尝试使用..... dorsal:parseInt(sReq.body.dorsal).... –因为typeof req.body.xxx ===“ string”;而背面类型:Number。因此,您必须使用parseInt方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM