Next.js Discord

Discord Forum

mongodb returns an error

Answered
plz mention when u reply :3 posted this in #help-forum
Open in Discord
so i'm trying to import a mongo database to my project with the following codes to integrate the discord login (basically, the user will authenticate their discord account and the data will be saved as a native account format):

// @/database/index.ts

import { connect } from 'mongoose'

export default async function () {
    return connect ('mongodb+srv://not:going@to.reveal.my.url/?retryWrites=true&w=majority')
}

// @/database/User.ts

import { Schema, model as Model } from 'mongoose'

const schema = new Schema ({
    // ...
}),
    model = Model ('user', schema)

export default model

// @/app/api/auth/route.tsx

import { NextRequest, NextResponse } from 'next/server'

import connect from '@/database'
import User from '@/database/User'

export async function POST (request: NextRequest) {
    await connect ()
    
    // ...

    const foundUser = await User.findOne ({ id: user.id })

    if (foundUser) return NextResponse.json (foundUser)

    const newUser = new User ({
        // ...
    }),
          savedNewUser = await newUser.save ()

    return NextResponse.json (savedNewUser)
}


but everytime i try to authenticate my account, it returns the following error:
- error Error [OverwriteModelError]: Cannot overwrite `user` model once compiled.

how can i solve this? thanks ^^
Answered by Blue-throated Hummingbird
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb-mongoose/models/Pet.js#L59

@plz mention when u reply :3 Try doing something similar to that, it worked for me
View full answer

10 Replies

(mention plz when reply)
@plz mention when u reply :3 (mention plz when reply)
you're registering the User schema again, register it once
no i'm nut
and assigned the schema and the model to a variable
but definitely:
Blue-throated Hummingbird
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb-mongoose/models/Pet.js#L59

@plz mention when u reply :3 Try doing something similar to that, it worked for me
Answer
it still errors in the development but works perfectly in prod
the dev one isn't that necessary since i'm not gonna make an open-source project
thankssss <3