Work with . and & in field names (TypeScript)
You must use & to escape any . or & in field names when the field is used in a filter, sort, projection, update, or indexing clause.
Dot notation, which is used to reference nested fields, should not be escaped.
For example, in the following document, you would use escaping like this: areas.r&&d, costs.price&.usd, and costs.price&.cad.
{
"areas": {
"r&d": true,
"design": false
},
"costs": {
"price.usd": 100,
"price.cad": 90
}
}
You should not escape . or & in field names when you insert or replace a document.
For example:
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Find a document
(async function () {
const result = await collection.findOneAndReplace(
{
$and: [{ "areas.r&&d": false }, { "costs.price&.usd": { $lt: 300 } }],
},
{
areas: {
"r&d": false,
design: true,
},
costs: {
"price.usd": 100,
"price.cad": 90,
},
},
{
projection: { "areas.r&&d": true, "costs.price&.usd": true },
sort: {
"areas.r&&d": 1,
"costs.price&.usd": -1,
},
},
);
console.log(result);
})();
You can also use the escapeFieldNames function provided by the client:
import {
DataAPIClient,
UsernamePasswordTokenProvider,
escapeFieldNames,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Find a document
(async function () {
const result = await collection.findOneAndReplace(
{
$and: [
{ [escapeFieldNames("areas", "r&d")]: false },
{ [escapeFieldNames("costs", "price.usd")]: { $lt: 300 } },
],
},
{
areas: {
"r&d": false,
design: true,
},
costs: {
"price.usd": 100,
"price.cad": 90,
},
},
{
projection: {
[escapeFieldNames("areas", "r&d")]: true,
[escapeFieldNames("costs", "price.usd")]: true,
},
sort: {
[escapeFieldNames("areas", "r&d")]: 1,
[escapeFieldNames("costs", "price.usd")]: -1,
},
},
);
console.log(result);
})();