JavaScript Function Call Causes "setUTCHours is not a Function"

Viewed 654

I have some MongoDB records with an OrderDate I wish to update the time component to midnight 00:00:00.000. The object is of the form

{
    "SourceSystem" : "XXXX" 
    "OrderDate" : {
        "DateTime" : ISODate("2017-11-29T00:00:00.000+00:00"),
        "Ticks" : 636475104000000000
    }
}

To do this I have the following JavaScript

function generateDate(targetDateTime){
    let ticks = targetDateTime.getTime() * 10000;
    ticks += 621355968000000000;
    return {
        DateTime: targetDateTime,
        Ticks: NumberLong(ticks)
    };
}

function datePartOnly(targetDateTime){
    targetDateTime.setUTCHours(0, 0, 0, 0);
    return generateDate(targetDateTime);
}

let orders = db.Orders.aggregate([
    {
        $match: {
            State: { $in: [ "Completed", "AwaitingExport" ] }, 
            SourceSystem: "Demon",
            OrderDate: {
                $gte: generateDate(ISODate("20200101")),
                $lt: generateDate(ISODate("20200701"))
            }
        }
    },
    {
        $addFields: {
            OrderDateString: {
                $dateToString: {
                    format: "%H%M%S.%L",
                    date: "$OrderDate.DateTime"
                }
            }
        }
    },
    {
        $match: {
            OrderDateString: /^((?!0{6}\.0{3})[\s\S])*$/
        }
    },
    {
        $project: { _id: 1 }
    }
]).toArray().map( o => o._id );

db.Orders.updateMany(
    {
        _id: { $in : orders }
    },
    {
        $set : {
            OrderDate: datePartOnly("$OrderDate.DateTime")
        }
    }
)

but I am getting the following error

"message" : "targetDateTime.setUTCHours is not a function", "stack" : "script:11:20" + "script:52:24"

Why is this call failing. I have tried using OrderDate: datePartOnly(ISODate("$OrderDate.DateTime")) but this gives

"message" : "invalid ISO date: $OrderDate.DateTime", "stack" : "script:1:37" + "script:1:37" + "script:52:37"

OrderDate: datePartOnly(Date("$OrderDate.DateTime")) does not work either.

What is wrong with the above?

1 Answers

By a small chance, is it possible the argument you are passing as targetDateTime is not a Date object (or any type with such function) ? This could explain why targetDateTime.setUTCHours is not a valid function.

Related