解决mongodb TypeError: Cannot read property 'XXX' of null 问题

有时候我们的字段里的数据为空而去查询就会报错。

比如以下形式:

“cartList”:[]

“cartList”:[{}]

“cartList”:{}

“cartList”:null

在查询的时候加上给可能为空的字段加上$exists。

以下内容抄自,感谢博主https://blog.csdn.net/yaomingyang/article/details/75116142

$exists语法: field: $exists: <boolean> }

1.当boolean为true,$exists匹配包含字段的文档,包括字段值为null的文档。

2.当boolean为false,$exists返回不包含对应字段的文档。

如下records集合:
{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }
{ b: 2, c: 4 }
{ b: 2 }{ c: 6 }
db.records.find( { a: { $exists: true } } )
查询结果是:
{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }

db.records.find( { b: { $exists: false } } )

  查询结果如下:

{ a: 2, c: 5 }
{ a: 4 }
{ c: 6 }

  

原文地址:https://www.cnblogs.com/qiu-freedom/p/10736182.html