Add Data to the Database using the Mongoose Schema
Now that we have a schema, we can use it to interact with MongoDB:
const mongoose = require('mongoose');
const Book = require('./models/book'); // Path to the Book model
// Connect to MongoDB
mongoose.connect('mongodb+srv://Abdullah:Abdullah123@cluster0.ihx3lfc.mongodb.net/node?retryWrites=true&w=majority');
// Insert books into the database
const books = [
{ title: "The Catcher in the Rye", author: "J.D. Salinger", year: 1951 },
{ title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 },
{ title: "1984", author: "George Orwell", year: 1949 },
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925 },
{ title: "Pride and Prejudice", author: "Jane Austen", year: 1813 }
];
// Insert multiple documents (books) into the collection
Book.insertMany(books)
.then(() => {
console.log('Books inserted successfully');
mongoose.connection.close(); // Close the connection after insertion
})
.catch((err) => {
console.error('Error inserting books:', err);
mongoose.connection.close(); // Close the connection on error
});
How to Use MongoDB and Mongoose with Node.js ?
In the world of Node.js development, MongoDB is a popular choice for database management due to its flexibility and scalability. When working with MongoDB in a Node.js environment, using Mongoose—a JavaScript library—makes the interaction with the database even more efficient and structured. In this article, we’ll explore how to integrate MongoDB and Mongoose into a Node.js application step by step.
Table of Content
- What is Mongoose?
- Steps to Create the NodeJS App And Installing Module
- Establish Mongoose MongoDB Node.js Connection
- Model a Schema using Mongoose
- Add Data to the Database using the Mongoose Schema
- Using Postman to Interact with MongoDB Data
- Conclusion