![](/img/trans.png)
[英]How to wrap controllers with a mongoDB session object, in express.js
[英]mongodb express.js find object in array
我有这个数据库“ 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!");
}
猫鼬的findOne
方法会收到一个可选的第二个参数,其中包含要选择的字段。
您应该这样查询:
dbo.collection("equipos").findOne(
{"team_name": sReq.body.nombre_equipo,
"players": {$elemMatch: {"dorsal": sReq.body.dorsal}}
}, function(err, res){
注意,要查询的两个字段都将作为第一个参数传递,第二个参数将是回调,因为在这种情况下,您不会告诉猫鼬选择哪个字段。
尝试使用..... dorsal:parseInt(sReq.body.dorsal).... –因为typeof req.body.xxx ===“ string”;而背面类型:Number。因此,您必须使用parseInt方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.