为什么我使用Mongo find()在Nodejs中获得未定义的结果

时间:2016-07-07 06:43:36

标签: node.js mongodb

Nodejs脚本:

var numberlist = db.collection('fsnumbers');

var getTotalforToday = function(){
        var curDate = moment().format('MMMM Do YYYY'); 
        curDate = "/"+curDate+"/i";

        numberlist.find({"date": { $regex: curDate } }, function(err, items){
            if(items){
                return items;
            }
        });

}

MongoDB控制台查询:

db.fsnumbers.find( { "date": { $regex: /July 7th 2016/i } } )

结果

{ "_id" : ObjectId("577d45c9b2b0e2e40a9187f1"), "numbers" : 5869437261, "date" : "July 7th 2016, 1:54:17 am" }
{ "_id" : ObjectId("577d45f9b2b0e2e40a9187f2"), "numbers" : 5862389712, "date" : "July 7th 2016, 1:55:05 am" }
{ "_id" : ObjectId("577d4606b2b0e2e40a9187f3"), "numbers" : 3138990309, "date" : "July 7th 2016, 1:55:18 am" }
{ "_id" : ObjectId("577dde97f38da37019eefb8c"), "numbers" : 3137208860, "date" : "July 7th 2016, 12:46:15 pm" }
{ "_id" : ObjectId("577ddea7f38da37019eefb8d"), "numbers" : 2484993963, "date" : "July 7th 2016, 12:46:31 pm" }
{ "_id" : ObjectId("577ddeb4f38da37019eefb8e"), "numbers" : 3136498218, "date" : "July 7th 2016, 12:46:44 pm" }
{ "_id" : ObjectId("577de75749d7317c0e5d2bc7"), "numbers" : 1444444444, "date" : "July 7th 2016, 1:23:35 pm" }
{ "_id" : ObjectId("577debcd3e1652b80f54f030"), "numbers" : 3345343443, "date" : "July 7th 2016, 1:42:37 pm" }
{ "_id" : ObjectId("577dec2ffc8631300d064fee"), "numbers" : 3454334345, "date" : "July 7th 2016, 1:44:15 pm" }

2 个答案:

答案 0 :(得分:0)

/July 7th 2016*/i

由于您的日期是July 7th 2016, 1:54:17 am之类的字符串,因此您需要在正则表达式末尾添加 * ,以允许任何字符串代表您的模式之后的小时。

您可以在此处找到更好的,无正则表达式的方法来查询日期: MongoDB/Mongoose querying at a specific date

答案 1 :(得分:0)

curDate = "/"+curDate+"/i";

您在那里创建了一个字符串,而不是正则表达式对象。

试试这个:

curDate = new RegExp(curDate, 'i');