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"));
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 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 }))
When I attempt the code below, I just get an empty return from MongoDB....
let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');
let testSchema = new mongoose.Schema({
username: String,
name: {
firstname: String,
lastname: String,
},
email: String,
employeeID: String
});
const testModel = mongoose.model('test', testSchema);
mongoose.connect('mongodb://localhost:27017/test', { useUnifiedTopology: true }, function(err, res) {
if (err) console.log(err);
else console.log('Connected to Mongo');
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
const port = 5000;
const server = app.listen(port, () => {
console.log('connected to port ' + port);
});
testModel.find({}).exec(function(err, res){
if (!err) {
console.log(res);
}
else {
console.log("Error");
}
})
BUT, when I use this code, it returns the data I'm looking for..... why?! Every other tutorial I have seen operates like the above.
let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');
let testSchema = new mongoose.Schema({
username: String,
name: {
firstname: String,
lastname: String,
},
email: String,
employeeID: String
});
const testModel = mongoose.model('test', testSchema, 'test');
mongoose.connect('mongodb://localhost:27017/test', { useUnifiedTopology: true }, function(err, res) {
if (err) console.log(err);
else console.log('Connected to Mongo');
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
const port = 5000;
const server = app.listen(port, () => {
console.log('connected to port ' + port);
});
testModel.find({}).exec(function(err, res){
if (!err) {
console.log(res);
}
else {
console.log("Error");
}
})
How can I fix this in my code, or is it something within Mongo updates that this is a requirement?
By default, mongoose pluralizes the name of the model when you call mongoose.model() to determine the collection name. In your first example, it will be looking in the tests collection for documents.
In the second example, you specify that the name of the collection should be test , which is why the behavior is different.
I tried to make a MEAN stack app, but my API fails to give my requested data.
server.js file:
const express = require("express");
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT;
const dburi = process.env.DB_URI;
//Routes
const volcanoesRoute = require('./api/routes/volcano.routes');
mongoose.Promise = global.Promise;
mongoose.connect(
dburi,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
},
).then(
() => {
console.log('Connected to mongoDB');
},
(err) => console.log('Error connecting to mongoDB', err),
{ useNewUrlParser: true }
);
//Express app
const app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/api/vulcanoes', volcanoesRoute);
app.listen(port, () => {
console.log(`running at port ${port}`);
});
Routes file:
const express = require('express');
const volcanoController = require('../controllers/volcanoController');
const router = express.Router();
router.get('/getallvulcanoes', volcanoController.getAllVolcanoes);
module.exports = router;
Controller file:
const VolcanoSchema = require('../models/volcano.models');
const getAllVulcanoes = (req, res) => {
VolcanoSchema.find((err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVolcanoes};
Model file
const mongoose = require('mongoose');
const VolcanoSchema = new mongoose.Schema({
Volcano_name:{
type: String,
},
Country:{
type: String,
},
Type:{
type: String,
},
Latitude:{
type: Number,
},
Longtitude:{
type: Number,
},
Elevation:{
type: Number,
},
});
module.exports = mongoose.model('Volcano', VolcanoSchema);
The thing is that i have a working example but most of the code is decrepitated... but it the respond is always giving me this
It would be nice if someone point out what i am doing wrong
EDIT: I switched to postgresql for my database hopefully this will work
You should fix the Controller (VulcanoSchema.find needs an empty object as parameter):
Controller file:
const VulcanoSchema = require('../models/vulcano.models');
const getAllVulcanoes = (req, res) => {
VulcanoSchema.find({}, (err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVulcanoes};
I started working on a MERN App and am trying to write a restful api. Code is working fine. But POST Requests are not working.
moviemodel.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Movie = new Schema(
{
name: { type: String, required: true },
time: { type: [String], required: true },
rating: { type: Number, required: true },
},
{ timestamps: true },
)
module.exports = mongoose.model('users', Movie)
moviectrl.js
const Movie = require('../models/moviemodel')
createMovie = (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a movie',
})
}
const movie = new Movie(body)
if (!movie) {
return res.status(400).json({ success: false, error: err })
}
movie
.save()
.then(() => {
return res.status(201).json({
success: true,
id: movie._id,
message: 'Movie created!',
})
})
.catch(error => {
return res.status(400).json({
error,
message: 'Movie not created!',
})
})
}
index.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
var MongoClient = require('mongodb').MongoClient;
const movieRouter = require('./routes/movierouter')
const app = express()
const apiPort = 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors())
app.use(bodyParser.json())
MongoClient.connect('mongodb://127.0.0.1:27017/cinema', { useNewUrlParser:
true }, function(err, client) {
const db = client.db('cinema')
if(err) throw err;
console.log('Successfully connected')
})
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.use('/api', movieRouter)
app.listen(apiPort, () => console.log(`Server running on port
${apiPort}`))
movierouter.js
const express = require('express')
const MovieCtrl = require('../controllers/moviectrl')
const router = express.Router()
router.post('/movie', MovieCtrl.createMovie)
router.put('/movie/:id', MovieCtrl.updateMovie)
router.delete('/movie/:id', MovieCtrl.deleteMovie)
router.get('/movie/:id', MovieCtrl.getMovieById)
router.get('/movies', MovieCtrl.getMovies)
module.exports = router
When I send a POST Request using the link localhost:3000/api/movie and send a JSON Data through Postman. There is no response.
https://imgur.com/a/l6GvDbu
I've tested your app and found that your database is hanging ...
Replace your database connection with this 😃:
const url = 'mongodb://localhost:27017/cinema';
mongoose.connect(url, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
}, console.log(`DB running on ${url}`));
https://imgur.com/gallery/q4Y0lW2
exports.createMovie = async(req,res){
try{
const create = await ModelName.create(req.body)
if(ceate){
res.send("created")
}else{
res.send("error")
}
}catch(err){
res.send(err)
}
}