vineet
vineet

Reputation: 14236

MongoError: can't convert from BSON type missing to Date

I am using mongoose 4.5.0 and trying to fetch data using aggregation but it fails.

Here is my node code:-

    ..
    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)
        })
   ..

here is query string after consoling :-

> 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"}}}]

Now, here error:-

{ 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' }

Upvotes: 1

Views: 8006

Answers (2)

Abhi
Abhi

Reputation: 3611

You are trying to use the $month operator on a String.

The problem is here:

 month: { $month: "$date" }

Your date field is something like: "2017-02-01T09:11:19.358Z"

which is a String and year: { $year: "$date" } this will work on that date string. But month is not. You have to convert the expression as follows:

{ $month: ISODate("2017-02-01T09:11:19.358Z") } ie 
{ $month: ISODate("$date") }

Will solve the issue.

Check more about month aggregator: https://docs.mongodb.com/manual/reference/operator/aggregation/month/

Upvotes: -1

joeytwiddle
joeytwiddle

Reputation: 31257

You are trying to use Mongo date operations (e.g. $year, $month, $day) on a field which is not a date.

The problem is with this part of your query:

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

Possibly some or all of your documents have no value in the date field.

(As you said, it was a typo, and your field had a different name!)

A similar problem was discussed here, where the value of the field was present, but not of type date.

Upvotes: 5

Related Questions