NodeJS Express Mongoose return empty [] - node.js

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};

Related

Node js - mongodb not responding

Need help, I am trying to learn nodejs from youtube. I have created below but not getting any response from browser. Can you please check below code and advise what I have missed??
if I removed the courseModel.find ... from course.js and just write resp.send("XYZ") its showing on browser otherwise nothing is showing. please help
seems something is missing in mangodb connection string
--index.js
const connection = require('./model/connection');
const express = require('express');
const app = express();
const handleBars = require('express-handlebars');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path');
const courseController = require('./controllers/course');
const server = http.createServer(app);
app.use(bodyParser.urlencoded({
extended: true,
}))
app.use("/course", courseController);
server.listen(3900, () => {
console.log("server is in running mode.");
});
--connection.js
const mongoose = require('mongoose');
var conn = mongoose.createConnection("mongodb://localhost:27017/learning", (err) => {
if (!err) {
console.log("Mongo db connected");
} else {
console.log(err);
}
});
const courseModels = require("./course.model");
--course.model.js
const mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
courseName: {
type: String,
required: 'Required'
},
courseId: {
type: String,
},
courseDuration: {
type: String,
}
});
module.exports = mongoose.model("Course", CourseSchema);
--course.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const courseModel = mongoose.model("Course");
router.get("/lists", (req, resp) => {
courseModel.find((err,docs)=>{
if(!err){
resp.send(docs)
}
});
});
module.exports = router;
--logs
issue resolved after updating the connection.js as below
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learning',
{
useNewUrlParser: true,
// useFindAndModify: false,
useUnifiedTopology: true
}, console.log("mongo db connected")
);
Insted of .
server.listen(3900, () => {
console.log("server is in running mode.");
});
use :
app.listen(3900, () => {
console.log("server is in running mode.");
});

How to fix post method error using ExpressJs and MongoDB

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"));

TypeError: Cannot read property 'username' of undefined in node.JS / express cannot post to route

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) => {

from nodejs app mongose.save() block and doesn't do anything?

I'm trying to use a very basic MongoDB method is to save a document on a database with mongoose.
1.I installed my MongoDB in centos 7
2.Create a database on the Mongo shell using: use mydatabase and insert a document inside it as normal.
3.Install mongoose and make a connection between my nodejs app and the MongoDB:
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
4. test the connection and all is fine with:
db.once('open', () => {
console.log('DB Connected');
});
Import the model schema as normal:
var { Classe } = require('../DBModels/GoClassDBModels/classes');
try to add new document like this:
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
newClasse.save()
My Model is:
const mongoose = require('mongoose');
const { Schema } = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model('Classes', classSchema);
module.exports = { Classe };
SERVER.JS:
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const cookieParser = require('cookie-parser');
const _ = require('lodash');
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log('server is started on 80');
});
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once('open', () => {
console.log('DB Connected');
});
db.on('error', (err) => {
console.log(err);
});
var { Classe } = require('../DBModels/GoClassDBModels/classes');
const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(['lakkini.com']));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
'Cache-Control',
'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
);
next();
});
app.set('view engine', 'hbs');
app.use(express.static('/home/admin/SMS'));
app.use(express.static('/home/admin/assets'));
app.get('/', (req, res) => {
res.render('SMS/dashboard.hbs');
});
app.get('/classes', (req, res) => {
res.render('SMS/classes.hbs');
});
app.get('/inscription', (req, res) => {
res.render('SMS/inscriptions.hbs');
});
app.post('/saveClasse', (req, res) => {
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
console.log('im gonna save the new class');
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log(response);
});
});
The problem is: nothing happened. No document has been inserted and no errors.
Can you suggest to me, please ?
PS: I'm trying to request from an HTTP server without HTTPS.
will that affect my requests nd block the save to the database?
result:
click to see the picture of the result please
Since the whole file was not given for mongoose connection and where save function is called , assuming you have structured it properly i'm giving my answer.
I was able to do this way,
The schema (same as yours) :
const mongoose = require("mongoose");
const { Schema } = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model("Classes", classSchema);
module.exports = { Classe };
Function to insert:
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("DB Connected");
var newClasse = new Classe({
label: "hello",
level: "level",
});
newClasse.save();
});
UPDATE:
SERVER.JS
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
const cookieParser = require("cookie-parser");
const _ = require("lodash");
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log("server is started on 80");
});
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once("open", () => {
console.log("DB Connected");
});
db.on("error", (err) => {
console.log(err);
});
var { Classe } = require("./models/Classe");
// const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(["lakkini.com"]));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
"Cache-Control",
"no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0"
);
next();
});
app.set("view engine", "hbs");
// app.use(express.static("/home/admin/SMS"));
// app.use(express.static("/home/admin/assets"));
// app.get('/', (req, res) => {
// res.render('SMS/dashboard.hbs');
// });
// app.get('/classes', (req, res) => {
// res.render('SMS/classes.hbs');
// });
// app.get('/inscription', (req, res) => {
// res.render('SMS/inscriptions.hbs');
// });
app.post("/saveClasse", (req, res) => {
var newClasse = new Classe({
label: "hello",
level: "level",
});
console.log("im gonna save the new class");
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log("RESPONSE" + response);
});
});
I found the issue, but I don't understand why that.
the first structure was:
**
DBModel
classes.js
Server
server.js**
the structure right now:
**
DBModel
classes.js
server.js
**
I make out the server from that folder and all working fine...??
why that?

POST Request not working - MongDB and Express JS using Mongoose

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)
}
}

Resources