2017-02-01 41 views
1

我正在使用mongoose 4.5.0並嘗試使用聚合獲取數據,但失敗。MongoError:無法從BSON類型轉換爲日期

這裏是我的結點代碼: -

.. 
    var preMonths = new moment().subtract(4, 'months').date(1).toDate();  //4:for 5 month 
    var match = { $and: [] }; 
    match.$and.push({ companyId: new ObjectID(req.user.companyId._id) }); 
    match.$and.push({ status: 'CONVERTED' }); 


    var allUnderUsers = []; 
    req.session.underUser.forEach(function(element, index) { 
     allUnderUsers.push(ObjectID(element)) 
    }); 
    match.$and.push({ assignTo: { $in: allUnderUsers } }); 

    match.$and.push({ createdOn: { $gt: preMonths, $lt: new moment().toDate() } }); 
    var aggregate = [ 
     { $match: match }, { 
      $group: { 
       _id: { month: { $month: "$date" },year: { $year: "$date" } }, 
       total: { $sum: '$value' } 
      } 
     } 
    ]; 
    console.log(JSON.stringify(aggregate)) 
    Lead.aggregate(aggregate) 
     .exec(function(err, data) { 
      if (err) 
       return next(err) 
      var temp = []; 
      data.forEach(function(element, index) { 
       temp.push([moment().month(element._id.month).format('MMM')+' '+element._id.year, element.total]); 
      }) 
      res.status(200).json(temp) 
     }) 
    .. 

這裏是安慰後查詢字符串: -

> console.log(aggreate)


> [{"$match":{"$and":[{"companyId":"5875bb5ba5a2f0e52f76ec6c"},{"status":"CONVERTED"},{"assignTo":{"$in":["587dbf58cab7be105d076516","587dcd3edca5f235f862fdfd","587e1002dca5f235f862fe03","587e1079ad90f640757d396a","587e1193af725041b6a41a4d","587e131faf725041b6a41a58","587f1705edf2fa25f0ed1935","5881a1ffc51165fbc30a2c60","58873cb9ca352ccf80337ccd"]}},{"createdOn":{"$gt":"2016-10-01T09:11:19.357Z","$lt":"2017-02-01T09:11:19.358Z"}}]}},{"$group":{"_id":{"month":{"$month":"$date"},"year":{"$year":"$date"}},"total":{"$sum":"$value"}}}]

現在,這裏的錯誤: -

{ MongoError: can't convert from BSON type missing to Date at Function.MongoError.create (/home/node_modules/mongodb-core/lib/error.js:31:11) at Socket. (/home/node_modules/mongodb-core/lib/connection/connection.js:306:22) at emitOne (events.js:96:13) at Socket.emit (events.js:188:7) at readableAddChunk (_stream_readable.js:172:18) at Socket.Readable.push (_stream_readable.js:130:10) at TCP.onread (net.js:542:20) name: 'MongoError', message: 'can\'t convert from BSON type missing to Date', ok: 0, errmsg: 'can\'t convert from BSON type missing to Date', code: 16006,
codeName: 'Location16006' }

+0

從錯誤「'不能從BSON類型丟失到日期'」 ,你能確保日期值不爲空 – MSD

+0

是的,日期值不爲空這裏是日期查詢日誌'「createdOn」: {「$ gt」:「2016-10-01T09:11:19.357Z」,「$ lt」:「2017-02-01T09:11:19.358Z」}' – vineet

+0

[例外:無法轉換BSON類型EOO到日期](http://stackoverflow.com/questions/28415995/exception-cant-convert-from-bson-type-eoo-to-date) –

回答

1

您正在嘗試使用Mongo日期操作(例如$year,$month,$day)在一個不是約會的領域。

問題是與您的查詢的這個部分:

_id: { 
    month: { $month: "$date" }, 
    year: { $year: "$date" } 
}, 

部分或全部的文檔都在date字段沒有值。

(正如你所說,這是一個錯字,和你的領域有不同的名字!)

類似的問題進行了討論here,其中字段的值存在,但不是類型的日期。

相關問題