在MongoDB中使用字符串函数indexOf()时出现this.*** is undefined异常的原因

案例如下:
集合(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()函数的一个缺陷吧,希望以后能够改进。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值