Mongoose
The nuxt-server-utils
module has built-in support for Mongodb with Mongoose. You don't need to create Nitro plugin for Mongoose, just install the module and you are ready to go.
Setup
yarn
yarn add mongoose
Configuration
Mongoose can be configured using .env file or nuxtServerUtils.mongodbUri
option in nuxt.config.ts
.
.env
MONGODB_URI=YOUR_MONGODB_URI
nuxt.config.ts
//...
nuxtServerUtils: {
mongodbUri: process.env.MONGODB_URI
},
Usage
You can access continue to use Mongoose as you would normally do.
Example
server/models/user.model.ts
import { Schema, model } from "mongoose";
const UserSchema = new Schema({
name: String,
email: String,
});
export const User = model("User", UserSchema);
server/api/users.get.ts
import { User } from "~~/server/models/user.model";
export default defineEventHandler(async (event) => {
const users = await User.find();
return Users;
});
Table of Contents