initial commit
This commit is contained in:
15
src/runtime/server/plugins/mongoose.db.ts
Normal file
15
src/runtime/server/plugins/mongoose.db.ts
Normal file
@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Due to an upstream bug in Nuxt 3 we need to stub the plugin here, track:https://github.com/nuxt/nuxt/issues/18556
|
||||
* */
|
||||
import type { NitroApp } from 'nitropack'
|
||||
import { defineMongooseConnection } from '../services/mongoose'
|
||||
|
||||
type NitroAppPlugin = (nitro: NitroApp) => void
|
||||
|
||||
function defineNitroPlugin(def: NitroAppPlugin): NitroAppPlugin {
|
||||
return def
|
||||
}
|
||||
|
||||
export default defineNitroPlugin(() => {
|
||||
defineMongooseConnection()
|
||||
})
|
||||
1
src/runtime/server/services/index.ts
Normal file
1
src/runtime/server/services/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export { defineMongooseConnection, defineMongooseModel } from './mongoose'
|
||||
36
src/runtime/server/services/mongoose.ts
Normal file
36
src/runtime/server/services/mongoose.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import type { ConnectOptions, Model, SchemaDefinition, SchemaOptions } from 'mongoose'
|
||||
import { Schema, connect, model } from 'mongoose'
|
||||
import { logger } from '@nuxt/kit'
|
||||
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
|
||||
export async function defineMongooseConnection({ uri, options }: { uri?: string; options?: ConnectOptions } = {}): Promise<void> {
|
||||
const config = useRuntimeConfig().public.mongoose
|
||||
const mongooseUri = uri || config.uri
|
||||
const mongooseOptions = options || config.options
|
||||
|
||||
try {
|
||||
await connect(mongooseUri, { ...mongooseOptions })
|
||||
logger.info('Connected to database')
|
||||
}
|
||||
catch (err) {
|
||||
logger.error('Error connecting to database', err)
|
||||
}
|
||||
}
|
||||
|
||||
export function defineMongooseModel(nameOrOptions: string | { name: string; schema: SchemaDefinition; options?: SchemaOptions }, schema?: SchemaDefinition, options?: SchemaOptions): Model<any> {
|
||||
let name: string
|
||||
if (typeof nameOrOptions === 'string') {
|
||||
name = nameOrOptions
|
||||
}
|
||||
else {
|
||||
name = nameOrOptions.name
|
||||
schema = nameOrOptions.schema
|
||||
options = nameOrOptions.options
|
||||
}
|
||||
|
||||
const newSchema = new Schema({
|
||||
...schema,
|
||||
}, { ...options })
|
||||
return model(name, newSchema)
|
||||
}
|
||||
Reference in New Issue
Block a user