Unable to use dates as a partitionkey using cosmos db binding

Issue:
Unable to use dates as a partitionkey using cosmos db binding in Function App.

Error message

1
2021-02-25T10:06:43.246 [Error] Executed 'Functions.DateAsPartitionKey' (Failed, Id=4b6caaf1-70b3-43f6-ad3b-6135690aaff8, Duration=989ms)Message: {"Errors":["PartitionKey extracted from document doesn't match the one specified in the header"]}ActivityId: 93031b95-f2b7-4671-be9b-d2b15bdbe699, Request URI: /apps/4ade04dd-f1a9-46ca-8ce8-d1d500ff6422/services/14f4e25c-4cdb-4c48-9698-7c2bd157131c/partitions/89f15a69-3e0b-4eac-88ed-4ec954b9d385/replicas/132587031061806885p/, RequestStats:RequestStartTime: 2021-02-25T10:06:42.9959386Z, RequestEndTime: 2021-02-25T10:06:42.9959386Z, Number of regions attempted:1ResponseTime: 2021-02-25T10:06:42.9959386Z, StoreResult: StorePhysicalAddress: rntbd://cdb-ms-prod-westeurope1-fd59.documents.azure.com:14396/apps/4ade04dd-f1a9-46ca-8ce8-d1d500ff6422/services/14f4e25c-4cdb-4c48-9698-7c2bd157131c/partitions/89f15a69-3e0b-4eac-88ed-4ec954b9d385/replicas/132587031061806885p/, LSN: 10, GlobalCommittedLsn: 10, PartitionKeyRangeId: 0, IsValid: True, StatusCode: 400, SubStatusCode: 1001, RequestCharge: 1.24, ItemLSN: -1, SessionToken: -1#10, UsingLocalLSN: False, TransportException: null, ResourceType: Document, OperationType: Upsert, SDK: Microsoft.Azure.Documents.Common/2.11.0, Windows/10.0.14393 documentdb-netcore-sdk/2.9.2

Sample Project:
index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

const dobDate = new Date(2012, 2, 2);
const dateItem = {
datepartition: dobDate
};
context.bindings.dataOut = JSON.stringify(dateItem);

context.res = {
// status: 200, /* Defaults to 200 */
body: dateItem
};
}

function.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get"
]
},
{
"name": "dataOut",
"type": "cosmosDB",
"direction": "out",
"databaseName": "staging",
"collectionName": "datecheck",
"createIfNotExists":"true",
"partitionKey": "datepartition",
"connectionStringSetting": "COSMOSDB_CONNSTRING"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}

Possible solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const CosmosClient = require("@azure/cosmos").CosmosClient;
const client = new CosmosClient({ endpoint:"YourCosmosDBEndpoint", key: "YourKey" });
const container = client.database("staging").container("datecheck");

module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

const dobDate = new Date(2012, 2, 2);
const dateItem = {
datepartition: dobDate
};

await container.items.create(dateItem);

context.res = {
// status: 200, /* Defaults to 200 */
body: dateItem
};
}

HTH. 2021-3-4 By Jacky