案例如下:
集合(collection):Com2;
原有文档(document)如下:
{ "_id" : ObjectId("5f58efd901f4ffc65c33de76"), "id" : 101, "name" : "Trump" }
{ "_id" : ObjectId("5f58efe601f4ffc65c33de77"), "id" : 102, "name" : "Tesla" }
{ "_id" : ObjectId("5f58eff001f4ffc65c33de78"), "id" : 103, "name" : "Maria" }
{ "_id" : ObjectId("5f58eff801f4ffc65c33de79"), "id" : 104, "name" : "Maylanie" }
{ "_id" : ObjectId("5f58f00001f4ffc65c33de7a"), "id" : 105, "name" : "Jhon5" }
{ "_id" : ObjectId("5f58f00901f4ffc65c33de7b"), "id" : 106, "name" : "Jhon6" }
{ "_id" : ObjectId("5f58f01301f4ffc65c33de7c"), "id" : 107, "name" : "Jhon7" }
即,所有document中的域(field)除了默认的_id外,还有id和name。
此时,使用字符串函数indexOf()查询时,情况是:
> db.Com2.find({$where:function(){return this.name.indexOf("a")==1}})
{ "_id" : ObjectId("5f58eff001f4ffc65c33de78"), "id" : 103, "name" : "Maria" }
{ "_id" : ObjectId("5f58eff801f4ffc65c33de79"), "id" : 104, "name" : "Maylanie" }
后来,又用for(i=0;i<6;i++){db.Com2.insert({_id:i})}批量插入了如下document:
{ "_id" : 0 }
{ "_id" : 1 }
{ "_id" : 2 }
{ "_id" : 3 }
{ "_id" : 4 }
{ "_id" : 5 }
新插入的这批document中,field只有默认的_id,此时再使用indexOf()查询时,虽然document总共有13条,但情况却变为:
> db.Com2.find({$where:function(){return this.name.indexOf('a')==1}})
Error: error: {
"ok" : 0,
"errmsg" : "TypeError: this.name is undefined :\n@:1:13\n",
"code" : 139,
"codeName" : "JSInterpreterFailure"
}
原因分析:就上述案例而言,当collection中不是所有的document中均有name这样的field时,使用indexOf()就会出现undefined异常。不过,这应该算是indexOf()函数的一个缺陷吧,希望以后能够改进。