Make a crud app using next js and mongoose ??
- User
Make a crud app using next js and mongoose ??
- Assistant
Make a crud app using next js and mongoose ??
Sure! Let's build a simple CRUD (Create, Read, Update, Delete) application using Next.js and Mongoose. In this example, we'll create a basic application to manage a list of books. We'll set up a Next.js project, connect to a MongoDB database using Mongoose, and implement API routes and pages for CRUD operations.
Create a new Next.js project:
npx create-next-app nextjs-mongoose-crud
cd nextjs-mongoose-crud
Install dependencies:
npm install mongoose
Create a new folder lib and inside it, create a file mongodb.js to set up the Mongoose connection.
mkdir lib
touch lib/mongodb.js
lib/mongodb.js:
import mongoose from 'mongoose';
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
throw new Error('Please define the MONGODB_URI environment variable inside .env.local');
}
/**
* Global is used here to maintain a cached connection across hot reloads in development.
* This prevents connections growing exponentially during API Route usage.
*/
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
async function dbConnect() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => mongoose);
}
cached.conn = await cached.promise;
return cached.conn;
}
export default dbConnect;
Create a .env.local file in the root directory and add your MongoDB connection string:
.env.local:
MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority
Replace <username>, <password>, and mydatabase with your actual MongoDB credentials.
Create a models folder and define a Book model.
mkdir models
touch models/Book.js
models/Book.js:
import mongoose from 'mongoose';
const BookSchema = new mongoose.Schema({
title: String,
author: String,
publishedDate: Date,
});
export default mongoose.models.Book || mongoose.model('Book', BookSchema);
Next.js allows us to create API routes inside the pages/api directory.
pages/api/books/index.js:
import dbConnect from '../../../lib/mongodb';
import Book from '../../../models/Book';
export default async function handler(req, res) {
await dbConnect();
const { method } = req;
switch (method) {
case 'GET':
try {
const books = await Book.find({});
res.status(200).json({ success: true, data: books });
} catch (error) {
res.status(400).json({ success: false });
}
break;
case 'POST':
try {
const book = await Book.create(req.body);
res.status(201).json({ success: true, data: book });
} catch (error) {
res.status(400).json({ success: false });
}
break;
default:
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}
pages/api/books/[id].js:
import dbConnect from '../../../lib/mongodb';
import Book from '../../../models/Book';
export default async function handler(req, res) {
await dbConnect();
const {
query: { id },
method,
} = req;
switch (method) {
case 'GET':
try {
const book = await Book.findById(id);
if (!book) {
return res.status(404).json({ success: false });
}
res.status(200).json({ success: true, data: book });
} catch (error) {
res.status(400).json({ success: false });
}
break;
case 'PUT':
try {
const book = await Book.findByIdAndUpdate(id, req.body, { new: true, runValidators: true });
if (!book) {
return res.status(404).json({ success: false });
}
res.status(200).json({ success: true, data: book });
} catch (error) {
res.status(400).json({ success: false });
}
break;
case 'DELETE':
try {
const deletedBook = await Book.deleteOne({ _id: id });
if (!deletedBook.deletedCount) {
return res.status(404).json({ success: false });
}
res.status(200).json({ success: true, data: {} });
} catch (error) {
res.status(400).json({ success: false });
}
break;
default:
res.setHeader('Allow', ['GET', 'PUT', 'DELETE']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}
pages/index.js:
import { useState, useEffect } from 'react';
import Link from 'next/link';
export default function Home() {
const [books, setBooks] = useState([]);
useEffect(() => {
fetch('/api/books')
.then((res) => res.json())
.then(({ data }) => {
setBooks(data);
});
}, []);
return (
<div>
<h1>Books</h1>
<Link href="/new">
<a>Add New Book</a>
</Link>
<ul>
{books.map((book) => (
<li key={book._id}>
<Link href={`/books/${book._id}`}>
<a>{book.title}</a>
</Link>
</li>
))}
</ul>
</div>
);
}
pages/new.js:
import { useState } from 'react';
import { useRouter } from 'next/router';
export default function NewBook() {
const [form, setForm] = useState({ title: '', author: '', publishedDate: '' });
const router = useRouter();
const handleChange = (e) => {
const { name, value } = e.target;
setForm((prevState) => ({ ...prevState, [name]: value }));
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await fetch('/api/books', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
router.push('/');
} catch (error) {
console.error('Failed to add the book');
}
};
return (
<div>
<h1>Add New Book</h1>
<form onSubmit={handleSubmit}>
<input name="title" placeholder="Title" onChange={handleChange} required />
<input name="author" placeholder="Author" onChange={handleChange} required />
<input name="publishedDate" type="date" onChange={handleChange} required />
<button type="submit">Add Book</button>
</form>
</div>
);
}
pages/books/[id].js:
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
export default function BookDetail() {
const router = useRouter();
const { id } = router.query;
const [book, setBook] = useState(null);
const [form, setForm] = useState({ title: '', author: '', publishedDate: '' });
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
if (id) {
fetch(`/api/books/${id}`)
.then((res) => res.json())
.then(({ data }) => {
setBook(data);
setForm({
title: data.title,
author: data.author,
publishedDate: data.publishedDate.split('T')[0],
});
});
}
}, [id]);
const handleDelete = async () => {
try {
await fetch(`/api/books/${id}`, {
method: 'DELETE',
});
router.push('/');
} catch (error) {
console.error('Failed to delete the book');
}
};
const handleEdit = async (e) => {
e.preventDefault();
try {
await fetch(`/api/books/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
setIsEditing(false);
setBook({ ...book, ...form });
} catch (error) {
console.error('Failed to update the book');
}
};
const handleChange = (e) => {
const { name, value } = e.target;
setForm((prevState) => ({ ...prevState, [name]: value }));
};
if (!book) return <p>Loading...</p>;
return (
<div>
{isEditing ? (
<form onSubmit={handleEdit}>
<input name="title" value={form.title} onChange={handleChange} required />
<input name="author" value={form.author} onChange={handleChange} required />
<input name="publishedDate" type="date" value={form.publishedDate} onChange={handleChange} required />
<button type="submit">Update Book</button>
</form>
) : (
<>
<h1>{book.title}</h1>
<p>{book.author}</p>
<p>{new Date(book.publishedDate).toDateString()}</p>
<button onClick={() => setIsEditing(true)}>Edit</button>
<button onClick={handleDelete}>Delete</button>
</>
)}
</div>
);
}
Start the development server:
npm run dev
Open your browser and navigate to http://localhost:3000 to see the application in action.
You now have a basic CRUD application using Next.js and Mongoose. This example demonstrates how to:
Remember to handle errors and edge cases in a production application, and consider adding features like authentication for secure operations.
Not yet included in a published release.