javascript - 为什么 Array.some 在 Mongo 的 $where 子句中不起作用?

标签 javascript arrays mongodb

我使用的是 MongoDB 1.8.1。我想在 $where 子句中模拟 Mongo 的 $elemMatch 查询,使用 JavaScript 数组上的标准 some 方法。但是,即使我提供了虚拟函数,查询也不会匹配任何内容。

> db.foo.insert({bar: [1, 2, 3]})
> db.foo.count({$where: 'this.bar && (this.bar.length > 0)'})
1
> db.foo.count({$where: 'this.bar && this.bar.some'})
1
> db.foo.count({$where: 'this.bar && this.bar.some(function() {return true;})'})
0

在 MongoDB shell 本身中,它可以工作:

> [1, 2, 3].some(function() {return true;})
true

这是为什么?

最佳答案

只需在 where 查询之前添加 return 即可工作

> db.foo.count({$where: 'return this.bar && this.bar.some(function() {return true;})'})
> 1
> db.foo.count({$where: 'return this.bar && this.bar.some(function(bar) {return bar>2;})'})
> 1
> db.foo.count({$where: 'return this.bar.some(function(bar) {return bar==1;}) &&  this.bar.some(function(bar) {return bar==6;})'})
> 0

但我更喜欢在 where claues 中使用函数而不是字符串,这样更干净

>db.foo.count({$where: function() { return  this.bar.some(function(bar) { return bar > 1;}) & this.bar.some(function(bar) { return bar > 2;}) }})
 >1

关于javascript - 为什么 Array.some 在 Mongo 的 $where 子句中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7415917/

相关文章:

Javascript 仅在 chrome 上打开 javascript 控制台时有效

javascript - Net.Socket 实例不会在 NodeJS 中消失

javascript - 回调是有条件地使用的吗?

MongoDB 允许磁盘使用不工作..

javascript - 在 Node.js 中导出 Mongoose 代码 - 将值从 Mongoose 方法传递给回调

javascript - 是否可以将 jQuery 动画 SPAN 元素嵌入到特定纬度和经度的 Google map 中?

javascript - 如何在jquery或js中创建动态二维数组

c++ - 从数组中获取一个 block

javascript - 从 jQuery 中的复选框的数组值中删除

javascript - 如何将数组从 html 发送到 node.js,然后再发送到 mongodb?