Search code examples
mongodbprisma

Prisma Schema: now() + X hours with Mongodb


I'm using Mongodb as the provider with Prisma. How can I set my expireAt field to be now()+15 hours for example?

datasource db {
    provider = "mongodb"
    url      = env("DATABASE_URL")
}

model UserToken {
    id                 String   @id @default(auto()) @map("_id") @db.ObjectId
    email              String   @unique
    createdAt          DateTime @default(now())
    expireAt           DateTime? @default(now() + XHours) // <-- ??
}

If I try to use dbgenerated("NOW() + interval '1 year'") for example, it gives an error saying:

Error validating field `expireAt` in model `UserToken`: 
The `dbgenerated()` function is not allowed with MongoDB. 
Please use `auto()` instead.

When I use auto() it says it doesn't accept any arguments. I'm looking to make it now()+X hours


Solution

  • This isn't possible at the moment. I would recommend creating a Feature Request so that setting a default time other than now() in MongoDB can be supported.

    For now, you would need to calculate expiredAt in your application code manually while creating a UserToken.

    In your application, you can do something like this to add 15 hours to the current time.

    let time = new Date();
    time.setHours(time.getHours() + 15);