require("dotenv").config();
const mongoose = require("mongoose");
const Author = require("./models/Author");
const Book = require("./models/Book");
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("✅ MongoDB Connected"))
.catch(err => console.log("❌ Connection Error:", err));
// 🌱 Seed Sample Data
const seedDatabase = async () => {
try {
await Author.deleteMany({});
await Book.deleteMany({});
const author1 = await new Author({ name: "J.K. Rowling", age: 57, nationality: "British" }).save();
const author2 = await new Author({ name: "George R.R. Martin", age: 74, nationality: "American" }).save();
await new Book({ title: "Harry Potter", genre: "Fantasy", author: author1._id }).save();
await new Book({ title: "Game of Thrones", genre: "Fantasy", author: author2._id }).save();
await new Book({ title: "A Clash of Kings", genre: "Fantasy", author: author2._id }).save();
console.log("✅ Database Seeded");
} catch (err) {
console.error("❌ Seeding Error:", err);
}
};
// 📚 Query Books with Author Data
const fetchBooksWithAuthors = async () => {
try {
const books = await Book.find().populate("author", "name nationality"); // Fetch author details
console.log("📖 Books with Authors:");
console.log(books);
} catch (err) {
console.error("❌ Query Error:", err);
} finally {
mongoose.connection.close();
}
};
// Run the Functions
(async () => {
await seedDatabase();
await fetchBooksWithAuthors();
})();