#types

24 messages · Page 1 of 1 (latest)

tranquil remnant
#

Hello, is it possible to import types for a table or query? I want to define a variable and set the type as a row of a table or null

sleek houndBOT
#

Hi @tranquil remnant. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, it is possible to import types for a table or query in Convex. Once you've defined a schema, Convex will produce new versions of dataModel.d.ts and server.d.ts with types based on your schema. The Doc<TableName> TypeScript type from dataModel.d.ts provides document types for all of your tables. You can use these types when writing Convex functions and in your React components.

Here is an example of how you can use these types:

import { Doc } from "../convex/_generated/dataModel";  
  
function MessageView(props: { message: Doc<"messages"> }) {  
  ...  
}  

In this example, Doc<"messages"> is the type for a row in the "messages" table. If you want to define a variable that can be a row of a table or null, you can use the Doc<TableName> type and include null as a possible value. For example:

let message: Doc<"messages"> | null = null;

In this case, message is a variable that can be a row from the "messages" table or null.

For more complex types, you can use the Infer type helper. If you want to create a type for a field in the schema, you can infer the type using Convex's Infer:

type MyType = Doc<'table_name'>['fieldName']

For the return type of a query, you can use FunctionReturnType<typeof api.foo.bla> as mentioned in the Discord support thread (https://discord.com/channels/1019350475847499849/1255545423112835122).

For more information, you can refer to the Convex documentation (https://docs.convex.dev/database/schemas#typescript-types).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@tranquil remnant kapa.ai is still learning and improving, please let us know how it did by reacting below

tranquil remnant
#

if i want to add a created_at / updated_at fields to my schema, what is the best way of doing it, and how should auto update it?

@sleek hound

sleek houndBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To add created_at and updated_at fields to your schema, you can simply add them to your table definition. Here's an example:

// schema.ts
import { defineTable, v } from "convex";

export const myTable = defineTable({
  // ... other fields
  created_at: v.optional(v.string()),
  updated_at: v.optional(v.string()),
});

In this example, both created_at and updated_at are optional string fields. You can also use v.number() if you prefer to store timestamps as numbers.

To automatically update these fields, you can do so in your mutation functions. When you create a new document, you can set created_at to the current time. When you update a document, you can set updated_at to the current time. Here's an example:

// myFunctions.ts
import { mutation } from "./_generated/server";

export const createDocument = mutation(async (ctx, args) => {
  return await ctx.db.insert("myTable", {
    ...args,
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString(),
  });
});

export const updateDocument = mutation(async (ctx, { id, ...args }) => {
  return await ctx.db.update("myTable", id, {
    ...args,
    updated_at: new Date().toISOString(),
  });
});

In these examples, new Date().toISOString() is used to get the current time as a string. If you're using numbers for your timestamps, you can use Date.now() instead.

#

Please note that _creationTime is a system field that is automatically generated by Convex when a document is created. It represents the time the document was created, in milliseconds since the Unix epoch. You can't manually set _creationTime on a mutation, it has to be created by the system. However, there is one way to set _creationTime on documents -- with a npx convex import as mentioned in the Discord support thread (https://discord.com/channels/1019350475847499849/1258108868030890014).

For more information, you can refer to the Convex documentation (https://docs.convex.dev/database/schemas#defining-a-schema).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@tranquil remnant kapa.ai is still learning and improving, please let us know how it did by reacting below

tranquil remnant
#

@sleek hound
so instead of creating my own "created_at" i can use _creationTime instead.
now make the updated_at field use the same " in milliseconds since the Unix epoch"

sleek houndBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, you can use the _creationTime field provided by Convex instead of creating your own created_at field. The _creationTime field is a system field that is automatically generated when a document is created and it represents the time the document was created, in milliseconds since the Unix epoch.

For the updated_at field, you can use the same format ("milliseconds since the Unix epoch") by using Date.now(), which returns the current time in milliseconds since the Unix epoch. Here's how you can do it:

// myFunctions.ts
import { mutation } from "./_generated/server";

export const updateDocument = mutation(async (ctx, { id, ...args }) => {
  return await ctx.db.update("myTable", id, {
    ...args,
    updated_at: Date.now(),
  });
});

In this example, Date.now() is used to get the current time in milliseconds since the Unix epoch. This will ensure that updated_at is in the same format as _creationTime.

For more information, you can refer to the Convex documentation (https://docs.convex.dev/database/schemas#defining-a-schema) and the Discord support thread (https://discord.com/channels/1019350475847499849/1212290186982199327).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@tranquil remnant kapa.ai is still learning and improving, please let us know how it did by reacting below

tranquil remnant
#

@sleek hound
what is the best practice in terms of field names on schemas?

sleek houndBOT
#

Let me check the knowledge base for you. One moment! :books:

#

When it comes to best practices for field names in schemas, there are a few general guidelines you can follow:

  1. Use descriptive names: Field names should clearly describe the data they hold. This makes your code easier to read and understand.

  2. Use lower case letters: It's a common practice to use lower case letters for field names. This helps to avoid confusion that can arise from case-sensitive names.

  3. Use underscores to separate words: If a field name consists of multiple words, you can use underscores (_) to separate them. For example, first_name, last_name, created_at, updated_at.

  4. Avoid special characters: As per the Discord support thread (https://discord.com/channels/1019350475847499849/1272890661636673666), field names should start with an alpha character. Avoid using special characters like &, +, -, etc. in field names.

  5. Consider using system fields: Convex provides system fields like _id and _creationTime that you can use instead of creating your own fields for document ID and creation time.

  6. Consider the type of data: If a field can have multiple types, Convex can handle this with a union type like v.union(v.number(), v.string()). This can be useful when you change your mind about the type of data a field should hold.

Remember, these are just guidelines and the specific naming conventions can vary depending on your project's requirements and the team's preferences. For more information, you can refer to the Convex documentation (https://docs.convex.dev/database/schemas#defining-a-schema).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@tranquil remnant kapa.ai is still learning and improving, please let us know how it did by reacting below

tranquil remnant
#

@sleek hound

should i use camelcase or snake case for field names?

what about indexes, should i use camelcase or snake case? i want to be consistent and follow the best practices

sleek houndBOT
#

Let me check the knowledge base for you. One moment! :books:

#

For field names in Convex, it's recommended to use snake_case (lowercase with underscores between words). This is in line with the general best practices for database schema design and also aligns with the examples provided in the Convex documentation.

Here's an example of a schema definition using snake_case:

// schema.ts
import { defineTable, v } from "convex";

export const myTable = defineTable({
  first_name: v.string(),
  last_name: v.string(),
  created_at: v.optional(v.string()),
  updated_at: v.optional(v.string()),
});

For indexes, the same naming convention applies. You should use snake_case for index names as well. Here's an example:

// schema.ts
import { defineTable, v } from "convex";

export const myTable = defineTable({
  first_name: v.string(),
  last_name: v.string(),
}).index("first_name_index", ["first_name"]);

In this example, first_name_index is the name of the index, which follows the snake_case convention.

For more information, you can refer to the Convex documentation (https://docs.convex.dev/database/schemas#defining-a-schema).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@tranquil remnant kapa.ai is still learning and improving, please let us know how it did by reacting below

tranquil remnant
#

@sleek hound
i want to create a field that accepts only one of this options

const send_status = ['not_started', 'not_active', 'active', 'finished'];

how to do it?

sleek houndBOT
#

Let me check the knowledge base for you. One moment! :books:

#

You can use the v.union function along with v.literal to create a field that only accepts one of the specified options. Here's how you can do it:

// schema.ts
import { defineTable, v } from "convex";

const send_status = ['not_started', 'not_active', 'active', 'finished'];

export const myTable = defineTable({
  // ... other fields
  send_status: v.union(...send_status.map(status => v.literal(status))),
});

In this example, v.union is used to create a type that can be any of the specified options, and v.literal is used to create a type that can only be a specific value. The map function is used to create a v.literal for each status.

For more information, you can refer to the Convex documentation (https://docs.convex.dev/database/schemas#literals).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: