I’m trying to integrate my Nuxt project with the nuxt-mongoose module.
(https://nuxt-mongoose.nuxt.space/getting-started/setup)
But I’m encountering a problem, even if I’ve followed all the steps.
First of all I installed the package
npm install nuxt-mongoose -D
Then I set up the .env and nuxt.config.ts
// nuxt.config.ts
export default defineNuxtConfig({
devtools: { enabled: true },
css: [
'vuetify/styles/main.sass'
],
build: {
transpile: ['vuetify']
},
modules: [
'nuxt-mongoose',
],
nitro: {
},
mongoose: {
uri: process.env.MONGODB_URI,
options: {},
modelsDir: 'models'
}
})
So I created a schema, following the wiki one
// server/models/user.schema.js
import {defineMongooseModel} from "#nuxt/mongoose"; //Here is where I'm getting the error
export const UserSchema = defineMongooseModel({
name: 'UserSchema',
schema: {
name: {
type: 'string',
required: true,
},
email: {
type: 'string',
required: true,
unique: true
},
password: {
type: 'string',
required: true
}
}
});
Even if I followed what’s in the wiki, when running npm run dev
, I’m getting this error:
ERROR Failed to resolve
import "#nuxt/mongoose" from "server\models\user.schema.js".
Does the file exist?
I’ve checked and actually the module export exists and so the method used, so I don’t know why it isn’t working.
I’ve tried to remove the import {defineMongooseModel} from "#nuxt/mongoose"
as seen in other internet pages, but then the error says that it doesn’t find that method.
I’ve tryied to remove and install the package nuxt-mongoose
multiple times, without success.
Upon checking the link you sent, your schema configuration is fine. The problem is, the codes inside the ~/pages/index.vue
. If I am not mistaken, files that are in the server are only accessible inside the server folder except the API routes.
The codes inside the index.vue
in the pages, and replace it with this.
<template>
<div>
<v-btn @click="saveTestUser()">Prova prova</v-btn>
</div>
</template>
<script setup lang="ts">
async function saveTestUser() {
console.log('clicked')
$fetch('/api/users/create', {
method: 'POST',
body: {
name: 'Giggio',
email: '[email protected]',
password: 'snmpassword'
}
}).then(() => {
console.log('Success')
}).catch((err) => {
console.log(err)
})
}
</script>
~/server/api/create.post.js
export default defineEventHandler( async ( event ) => {
try {
const body = await readBody( event )
await UserSchema.create( body )
return 200
} catch ( error ) {
console.log( error )
return createError( { statusCode: 500, statusMessage: 'Something went wrong.' } )
}
} )
Tested and it works!
Should that not be
@nuxt/mongoose
, importing from a scoped package?@jonrsharpe Actually no, also in the official wiki I linked it uses
#nuxt/mongoose
, and to other people seems to work, so I think that is not a problem related to the import itselfWhat version you are using?
@ReaganM here’s the package.json pastebin.com/CK3QbiJj
I tested the module based on your configuration and it’s working on my end
Show 3 more comments