SomeId: SomeIdTypes[keyof SomeIdTypes]
Overview

Represents all possible types for a document ID, including any JSON scalar types, Date, UUID, and ObjectId.

⚠️Warning: The _id can be set to null null.

Setting _id: null doesn't mean "auto-generate an ID" like it may in some other databases; it quite literally means "set the id to be null".

It's heavily recommended to properly type this in your Schema, so you know what to expect for your _id field.

💡Tip: You may mitigate this concern on an untyped collections by using a type such as—substituting string for your desired id type—{ _id: string } & SomeDoc, which would allow the collection to remain untyped while still statically enforcing the _id type.

Example

interface User {
_id: string,
name: string,
}

const result = await db.collection<User>('users').insertOne({
name: 'John',
});

console.log(result.insertedId.toLowerCase()); // no issue; _id is string

Example

const result = await db.collection<{ _id: string } & SomeDoc>('users').insertOne({
name: 'John',
});

console.log(result.insertedId.toLowerCase()); // also okay; _id is string

Example

const result = await db.collection('users').insertOne({
name: 'John',
});

console.log(result.insertedId.toLowerCase()); // type error; _id may not be string

The default ID

By default, if no _id field is provided in an inserted document, it will be automatically generated and set as a string UUID (not an actual UUID type).

You can modify this behavior by changing the CollectionDefinition.defaultId type when creating the collection; this allows it to generate a UUID or ObjectId instead of a string UUID.

See CollectionDefaultIdOptions.type for the exact types available.

Example

import { UUID } from '@datastax/astra-db-ts';

const collection = db.collection('users', {
defaultId: { type: 'uuid' },
});

const result = await collection.insertOne({
name: 'John',
});

console.log(result.insertedId); // UUID('123e4567-e89b-12d3-a456-426614174000')

Expanding SomeId

In case you need to expand the enumeration of valid types for _id, you can do so by expanding the SomeIdTypes interface via declaration merging.

⚠️Warning: This is an advanced feature, and should only be used if you really need to use a type for the _id field which isn't present in SomeId for whatever reason.

See SomeIdTypes for more information.