javascript - MongoDB $where 可选字段

标签 javascript mongodb

我正在创建一个 MongoDB 查询,返回今天生日的用户,因此我在 $where 语句中创建了这个 JS 函数:

function() {
    if (! this.birthday.getMonth) {return false;}

    return this.birthday.getMonth() == 1
    && this.birthday.getDate() == 1
}

不幸的是,if 语句似乎不起作用,因为如果未为文档设置生日字段,则会出现错误:

JS Error: TypeError: this.birthday has no properties nofile_18

欢迎任何帮助。

最佳答案

假设生日字段存储为Date或ISODate类型,您可以使用聚合框架进行正确的比较。我认为它会比启动 javascript shell 的 $where 更快。

// construct "thisMonth" variable which is current month as a number
// and thisDay which is current date of the month as a number
> var thisMonth = 5;
> var thisDay = 1;
> db.people.aggregate( [ 
        {$project:{month:{$month:"$birthday"}, date:{$dayOfMonth:"$birthday"}}},
        {$match: {month:thisMonth, date: thisDay}}
  ] )

关于javascript - MongoDB $where 可选字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322349/

相关文章:

javascript - promise mongodb 和 nodejs 中的未决错误

javascript - 如何为 Highcharts 饼图设置单独的颜色

javascript - <span> 光标未按预期工作

javascript - 如何在div中添加元素

javascript - Cycle2 图像类别

json - Node.js 服务器 : JSON. 字符串化深层对象

MongoDB 使用另一个集合中的另一个字段更新字段

mongodb - 如何在角度 5 中实现无限滚动分页?

mongodb - Mongodb 按索引字段搜索

JavaScript 未实现错误