This Express app connects to a MongoDB database with authors and books. When you visit /books, it returns all books with full author info filled in automatically using populate.
import express from 'express';
import mongoose from 'mongoose';
const app = express();
// Define schemas
const authorSchema = new mongoose.Schema({ name: String });
const bookSchema = new mongoose.Schema({ title: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' } });
// Create models
const Author = mongoose.model('Author', authorSchema);
const Book = mongoose.model('Book', bookSchema);
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/library');
app.get('/books', async (req, res) => {
try {
// Find books and populate author details
const books = await Book.find().populate('author').exec();
res.json(books);
} catch (err) {
res.status(500).send(err.message);
}
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));