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
const result = await db.collection<{ _id: string } & SomeDoc>('users').insertOne({
name: 'John',
});
console.log(result.insertedId.toLowerCase()); // also okay; _id is string
const result = await db.collection('users').insertOne({
name: 'John',
});
console.log(result.insertedId.toLowerCase()); // type error; _id may not be string
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.
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')
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.
Overview
Represents all possible types for a document ID, including any JSON scalar types,
Date
,UUID
, andObjectId
.It's heavily recommended to properly type this in your Schema, so you know what to expect for your
_id
field.