I am building a REST api service with Node, Express and MongoDB (A tutorial). I installed MongoDB and it runs normally on my PC on localhost:3000. In my server.js file I have this setup var express = require(‘express’); var mongoose = … I am getting this error as I post a POST command to mongoDB database. { “error”: “Validation Error” }. Please help.
Server.js
const express = require('express');
var mongoose = require('mongoose');
// Database connection and model.
require('./db/mongoose.js')();
const Book = require('./models/book.js');
// This creates our Express App.
const app = express();
// Define middleware.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Listening on port 3000 (arbitrary).
// Not a TCP or UDP well-known port.
// Does not require superuser privileges.
const PORT = 3000;
const bookData = {
"book": {
"title": "The Art of Computer Programming",
"isbn": "ISBN-13: 978-0-201-89683-1",
"author": {
"firstName": "Donald",
"lastName": "Knuth"
},
"publishingDate": "July 17, 1997",
"finishedReading": true
}
}
const book = new Book(bookData);
// We will build our API here.
// HTTP POST /books
app.post('/books', async (req, res) => {
try {
const book = new Book(req.body.book);
await book.save();
return res.status(201).send({ book });
} catch(e) {
if(e instanceof mongoose.Error.ValidationError) {
return res.status(400).send({ error: 'Validation Error' });
} else {
return res.status(500).send({ error: 'Internal Error' });
}
}
})
// HTTP GET /books/:id
app.get('/books/:id', (req, res) => {
// ...
console.log(`A GET Request was made! Getting book ${req.params.id}`);
});
// HTTP PATCH /books/:id
app.patch('/books/:id', (req, res) => {
// ...
console.log(`A PATCH Request was made! Updating book ${req.params.id}`);
});
// HTTP DELETE /books/:id
app.delete('/books/:id', (req, res) => {
// ...
console.log(`A DELETE Request was made! Deleting book ${req.params.id}`);
});
// Binding our application to port 3000.
app.listen(PORT, () => console.log(`Server is up on port ${PORT}.`));
mongoose.js
var mongoose = require('mongoose');
const MONGODB_URL = "mongodb+srv://tunji545:password@omisakinolatunji.chcjw.mongodb.net/dbname?retryWrites=true&w=majority";
module.exports = () => mongoose.connect(MONGODB_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});