Skip to content

Commit

Permalink
Saved a new book with mongoose
Browse files Browse the repository at this point in the history
  • Loading branch information
IsmailAkram committed Dec 3, 2023
1 parent 0f1b193 commit a7fb2c3
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 3 deletions.
30 changes: 30 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
import express from "express";
import { PORT, mongoDBURL } from "./config.js";
import mongoose from "mongoose";
import { Book } from "./models/bookModel.js";

This comment has been minimized.

Copy link
@IsmailAkram

IsmailAkram Dec 3, 2023

Author Owner

Corrected bookModels.js to bookModel.js


const app = express();

// Middleware for parsing JSON request body
app.use(express.json());

app.get("/", (request, response) => {
console.log(request);
return response
.status(200)
.send("Welcome to the MERN stack project, Bibliomania!");
});

// Route for saving a new book
app.post("/books", async (request, response) => {

This comment has been minimized.

Copy link
@IsmailAkram

IsmailAkram Dec 3, 2023

Author Owner

working with mongoose is an asynchronous process

try {
if (
!request.body.title ||
!request.body.author ||
!request.body.publishYear
) {
return response.status(404).send({
message: "Please send all required fields: title, author, publishYear",
});
}
const newBook = {
title: request.body.title,
author: request.body.author,
publishYear: request.body.publishYear,
};

const book = await Book.create(newBook);
return response.status(201).send(book);
} catch (error) {
console.log(error.message);
response.status(500).send({ message: error.message });
}
});

mongoose
.connect(mongoDBURL)
.then(() => {
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion backend/node_modules/tr46/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dependencies": {
"express": "^4.18.2",
"mongoose": "^8.0.2",
"nodemon": "^3.0.1"
"nodemon": "^3.0.1",
"punycode": "^2.3.1"
}
}

1 comment on commit a7fb2c3

@IsmailAkram
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image
We use the PUT method in Postman to save a book into the database using mongoose.

Please sign in to comment.