Integrate AdminJS with Mongoose Database: A Comprehensive Guide

AdminJS is a modern, powerful, and user-friendly admin panel for managing application data. In this guide, we will walk you through integrating AdminJS with a Mongoose database in a Node.js application.

Prerequisites

Before we start, ensure you have the following installed:

Step 1: Set Up Your Node.js Project

First, create a new Node.js project.

mkdir adminjs-mongoose
cd adminjs-mongoose
npm init -y

Step 2: Install Required Packages

Install the necessary packages including AdminJS, Mongoose, Express, and their adapters.

npm install adminjs @adminjs/express @adminjs/mongoose express mongoose

Step 3: Set Up Mongoose

Create a models directory and add a User.js file to define your Mongoose schema.

// models/User.js
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  role: { type: String, required: true, enum: ['admin', 'user'] },
});

module.exports = mongoose.model('User', UserSchema);

Step 4: Configure AdminJS

Create an admin directory and add a admin.js file to configure AdminJS.

// admin/admin.js
const AdminJS = require('adminjs');
const AdminJSExpress = require('@adminjs/express');
const AdminJSMongoose = require('@adminjs/mongoose');
const mongoose = require('mongoose');
const User = require('../models/User');

AdminJS.registerAdapter(AdminJSMongoose);

const adminJs = new AdminJS({
  resources: [User],
  rootPath: '/admin',
});

const router = AdminJSExpress.buildRouter(adminJs);

module.exports = { adminJs, router };

This code configures AdminJS to manage Mongoose models within an express application. It imports necessary modules, registers the Mongoose adapter with AdminJS, and sets up an AdminJS instance with a specified resource and root path, creating an express router for AdminJS which is then exported for use in the main application.

Elevate Your Node.js Applications with Seamless AdminJS Integration. Hire Our Developers Now!

Step 5: Set Up Express Server

Create an index.js file to set up your express server and connect to MongoDB.

// index.js
const express = require('express');
const mongoose = require('mongoose');
const { adminJs, router } = require('./admin/admin');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

app.use(adminJs.options.rootPath, router);

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 6: Create Environment Variables

Create a .env file in the root of your project to store environment variables.

// .env
MONGODB_URI=mongodb://localhost:27017/adminjs-mongoose

Step 7: Run Your Application

Start your application with the following command:

node index.js

Your AdminJS panel should be running at:

http://localhost:3000/admin.

Customizing AdminJS

You can customize the appearance and behavior of AdminJS. For example, you can add more resources, customize actions, and set up different themes.

Adding More Resources

To add more resources, create additional Mongoose models and add them to your AdminJS configuration.

// admin/admin.js
const Post = require('../models/Post'); // Assuming you have another model named Post

const adminJs = new AdminJS({
  resources: [User, Post],
  rootPath: '/admin',
});

Customizing Actions

You can customize the actions available for your resources. For example, you might want to customize the ‘new’ action for the user model.

// admin/admin.js
const adminJs = new AdminJS({
  resources: [{
    resource: User,
    options: {
       actions: {
         new: {
           before: async (request) => {
             if (request.payload.role === 'admin') {
                // Perform some action before creating an admin user
             }
             return request;
           },
         },
        },
      },
   }],
   rootPath: '/admin',
});
coma

Conclusion

In this blog post, we’ve set up AdminJS with a Mongoose database in a Node.js application. AdminJS provides a powerful and flexible way to manage your application data through an admin panel. With its easy setup and extensive customization options, AdminJS is a great choice for any Node.js project.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?