I am trying to make this web page to upload the books and there links but it always show the following error
const mongoose = require('mongoose');
const BookSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
authour: {
type: String,
required: true
},
discription: {
type: String,
},
link: {
type: String,
required: true
}
})
const Book = mongoose.model('books', BookSchema);
module.exports = Book ;
This is the schema I am using but it keeps showing
UnhandledPromiseRejectionWarning:
ValidationError: books validation failed: link: Path `link` is required., authour: Path `authour` is
required., name: Path `name` is required. at
model.Document.invalidate (E:\mystletainn\node_modules\mongoose\lib\document.js:2688:32) a
app.js code that I have been using
const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
//const methodOverride = require('method-override')
const books = require('./models/books');
mongoose.connect('mongodb://localhost:27017/books', { useNewUrlParser: true, useUnifiedTopology: true
})
.then(() => {
console.log("MONGO CONNECTION OPEN!!!")
})
.catch(err => {
console.log("OH NO MONGO CONNECTION ERROR!!!!")
console.log(err)
})
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views'))
app.use(express.urlencoded({ extended: true }));
//app.use(methodOverride('_method'))
app.get('/', async (req, res) => {
const { name } = req.query;
if (name) {
const book = await books.find({name})
res.render('main', { book, name })
} else {
const book = await books.find({})
res.render('main', { book })
}
})
app.get('/upload', async (req, res) => {
const { name } = req.query;
if (name) {
const book = await books.find({name})
res.render('/', { book, name })
} else {
const book = await books.find({})
res.render('upload',{book})
}
})
app.post('/', async (req, res) => {
const newBook = new books(req.body);
// await newBook.save();
console.log(newBook)
res.redirect(`/`)
})
app.listen(3000, () => {
console.log("LISTENING ON PORT 3000")
})
I have tried to resolve it but it is always giving the same error I am not able to save this to the const newbook.even the console.log shows only the id not the form data
You have to set link.required to false or send it with your request body.
You need to change your post method in something like that,
const newBook = new books({
name:req.body.name,
authour:req.body.author,
discription:req.body.description,
link:req.body.link
})
Related
I want to create an ESN and save it in my database
I'm using Nodejs and Mongodb
you can find the model, route and controller that I have created, what I want is a simple POST API to add an ESN to my data base.
Models
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const esnSchema = new Schema({
esnName: {
type: String,
required: true,
},
esnEmail: {
type: String,
required: true,
},
esnLogo: {
data: Buffer,
contentType: String,
required: false,
}
})
module.exports = mongoose.model("Esn",esnSchema);
Controllers
const Esn = require('../models/esn');
// create new ESN
const createEsn = async (req, res) => {
if (!req.body.esnName) {
res.status(400).send({ message: "Content can not be empty!" });
return;
}
const esn = new Esn({
esnName: req.body.esnName,
esnEmail: req.body.esnEmail,
esnLogo: req.body.esnLogo
});
// Save Esn in the database
esn
.save(esn)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the esn"
});
});
};
module.exports = {
createEsn
};
Routes
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const esnSchema = new Schema({
esnName: {
type: String,
required: true,
},
esnEmail: {
type: String,
required: true,
},
esnLogo: {
data: Buffer,
contentType: String,
required: false,
}
})
module.exports = mongoose.model("Esn",esnSchema);
index.js
const express = require('express'),
cors = require('cors'),
swaggerUi = require('swagger-ui-express'),
swaggerDocument = require('./docs/swagger.json');
const Mongo = require('mongodb');
const { default: mongoose } = require('mongoose');
const mainRoutes = require('./routes/esn')
const app = express();
var url = "mongodb://127.0.0.1:27017/";
var databasename = "skills";
Mongo.MongoClient.connect(url).then((client) => {
console.log('Database connected');
const connect = client.db(databasename);
//const collection = connect.createCollection("esn");
console.log('Database: ', connect);
}).catch((err) => {
// Handling the error
console.log(err.Message);
})
app.use(cors());
app.use(express.json());
app.listen(3000, () => {
console.log('Listening on port 3000!');
});
app.get('/', (req, res) => {
res.send('Hello World');
});
app.use('/api/', mainRoutes);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
I expected to save an esn in the database but I have this error
enter image description here
I'm new in Express.js,MongoDb and mongoose, I have created HTTP request methods, but when running the Post method, nothing is done (nothing saved in the database), and postman still loading and it stops only when I cancel. I want to know what's wrong in my code, thank you .
router.post("/v1/department", async (req, res) => {
try {
const request = req.body
const department = new Department(request)
await department.save()
res.status(200).send(department)
} catch (error) {
res.status(500).send(error)
}
});
This is my model
const mongoose = require("mongoose");
const validator = require('validator')
const Department = mongoose.model('Department', {
name: {
type: String,
required: true,
}
,
email: {
type: String,
required: true,
trim: true,//
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email!')
}
}
}
,
createdBy: {
type: String,
default: 'SYS_ADMIN'
}
,
updatedBy: {
type: String,
default: 'SYS_ADMIN'
}
,
createdAt: {
type: Date
// ,
// default: Date.getDate()
}
,
updatedAt: {
type: Date
// ,
// default: Date.getDate()
},
isDeleted: {
type: Boolean,
default: false
}
})
module.exports = Department
This is the Index.js
const express = require("express");
const app = express()
const departmentRouter = require("../src/routes/department")
app.use(express.json())
app.use(departmentRouter)
//app.use('/', require('./routes/department'))
const port = process.env.PORT || 5000;//local machine port 3000
app.listen(port, () => (`Server running on local machine port ${port} 🔥`));
The connection to the database is :
const mongoose = require("mongoose");
//Connect to the local mongoDB database for testing the API localy
mongoose.connect('mongodb://127.0.0.1:27017/openemp-api-department', {
useNewUrlParser: true,
useCreateIndex: true
})
You're missing a few things here. Mongoose is never set up in the index.js so there is no connection to the database. This should help you follow step by step
Also in your router you're sending department1 which is never assigned.
If the link doesn't work or you need more information let me know.
For the latest version of Express which is (Express v4.16.0 and higher)
Use this in your server.js file: ----->
const express = require('express');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
// For Express version less than 4.16.0
// ------------------------------------
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
otherwise your post request will give you error(like not recognizing any names etc)
so make sure to use these according to to express version
index.js file
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const axios = require("axios");
mongoose.connect(
"YourMongoUri",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
const dataSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
});
const modelData = mongoose.model("modelData", dataSchema);
router.get("/", (req, res) => {
modelData.find((err, doc) => {
if (err) console.log(err.message);
else {
res.send(doc);
}
});
});
router.post("/", (req, res) => {
const user = new modelData({
name: req.body.name,
age: req.body.age,
});
user.save((err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
router.put("/:id", (req, res) => {
const user = modelData.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
age: req.body.age,
},
(err, doc) => {
if (err) return console.log(err);
res.send(doc);
}
);
});
router.delete("/:id", (req, res) => {
modelData.findByIdAndDelete(req.params.id, (err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
module.exports = router;
server.js file
const express = require("express");
const myRouter = require("./index");
const app = express();
const port = 3000;
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
s;
app.use("/myroute", myRouter);
app.listen(port, console.log("listening on port 3000"));
I am using Nodejs, MongoDB and Mongoose and while making a POST request I am getting error:
POST http://localhost:3000/subscribers
Content-Type: application/json
{
"name": "Lucky",
"subscribedToChannel": "Dev Tech"
}
Error: {
"message": "Subscriber validation failed: name: Path name is required., subscribedToChannel: Path subscribedToChannel is required."
}
The code snippet is mentioned below:
server.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
mongoose.connect(mongodb://localhost/subscribers, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
app.use(express.json())
const subscribersRouter = require('./routes/subscribers')
app.use('/subscribers', subscribersRouter)
app.listen(3000, () => console.log('Server Started'))```
---------------------------------------------------------------------------------------------------
routers/subscribers.js
const express = require('express')
const router = express.Router()
const Subscriber = require('../models/subscriber')
// Creating one
router.post('/', async (req, res) => {
const subscriber = new Subscriber({
name: req.body.name,
subscribedToChannel: req.body.subscribedToChannel
})
try {
const newSubscriber = await subscriber.save()
res.status(201).json(newSubscriber)
} catch (err) {
res.status(400).json({ message: err.message })
}
})
module.exports = router
----------------------------------------------------------------------------------------------------
models/subscriber.js
const mongoose = require('mongoose')
const subscriberSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
subscribedToChannel: {
type: String,
required: true
},
subscribeDate: {
type: Date,
required: true,
default: Date.now
}
})
module.exports = mongoose.model('Subscriber', subscriberSchema)
[1]: https://i.stack.imgur.com/rHf38.jpg
Use bodyParser above app.use(express.json())
Like : app.use(bodyparser.urlencoded({ extended : false }))
I keep getting a type Error when posting to my exercises. here is my exercises route:
const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("error: " + err));
});
//add an exercise
router.route("/add").post((res, req) => {
//parse req.body
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
//create new exercise object
const newExercise = new Exercise({
username,
description,
duration,
date
});
//save newExercise object
newExercise
.save()
.then(() => res.json("Exercise Added!"))
.catch(err => res.status(400).json("error: " + err));
});
module.exports = router;
and here is my model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
{
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
},
{
timestamps: true
}
);
const Exercise = mongoose.model("Exercise", exerciseSchema);
module.exports = Exercise;
I've tried to change the route to router.post instead of router.route, I've tried changing the data model.
as well as my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();
//environment
const port = process.env.PORT || 5000;
//mongoose establish connection
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB connection established successfully");
});
//routers for users and exercises
const exercisesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");
app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);
//error log
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(`error: ${err}`).next();
});
app.listen(port, () => {
console.log(`server is up and running on port: ${port}`);
});
Here is the error logged in Insomnia:
Any Help is greatly appreciated!
You are misplace req and res in router.route("/add").post((res, req) => {.
Fix it: router.route("/add").post((req, res) => {
I am new to node and creating api.
I am able to pass a json in request body and log it on console ,but problem is arising when I am trying to add this data to my database .
I am trying to add data to DB(cloud:Atlas) but post.save is not running .
This is my post.model.js
const mongoose = require('mongoose')
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Posts', PostSchema)
This is controller (posts.js)
const express = require('express')
const router = express.Router()
const Posts = require('../model/posts.model')
router.get('/', (req, res) => res.send('We are on posts page'))
router.get('/specific', (req, res) => res.send('We are on specific post page'))
router.post('/', async (req, res) => {
const post = new Posts({
title: req.body.title,
description: req.body.description
})
// try{
// const savedPost = await this.post.save()
// res.json(savedPost)
// }
// catch(arr){
// res
// }
console.log('before save');
post.save().then(data => {
console.log("in then");
res.json(data)
})
.catch(err => {
console.log('in catch');
res.json({ message: err })
})
})
module.exports = router
This is my app.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const bodyParser =require('body-parser')
require('dotenv/config')
//Import Routes
const postsRoutes = require('./routes/posts')
//Middelware
app.use(bodyParser.json())//to be used before app.use(<routes>)
app.use('/posts', postsRoutes)
//app.use(express.bodyParser())
//ROUTES
app.get('/', (req, res) => res.send('We are on home page'))
app.get('/posts', (req, res) => res.send('WE are on posts page '))
//Connect to DB
mongoose.connect('DB_CONNECTION', { useNewUrlParser: true }, () => console.log('Connected to db'))
//how to start listening to the server
app.listen(3000)
Console
This is the req body:
Also when will collections form in my database?
Will it happen when I add first entry of data?
You aren't connected to your monogodb. You have to add the ip address and the name of the database.
In case there is not database with this name, it's going to create a new one.
mongoose.connect('mongodb://localhost/myDB', {
useNewUrlParser: true
});