MongoDB .find problems NodeJS - node.js

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.

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

NodeJS Express Mongoose return empty []

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

mongodb: Database not showing up in show dbs after data is inserted

I am following a YouTube tutorial from Jose Annunziato. I created my server.js and did all the required settings and configurations for my database connection. Now when I am posting something from the form to the server: it shows the data is sent to the server successfully but when I go to the mongo console to verify if the data is received and database is created or not. I run db it says test I run show dbs and there I can't see my new Database. I am not sure what the actual problem is because I did everything Jose said in the tutorial.
Server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogfall2016');
var PostSchema = mongoose.Schema({
title: {type: String, required: true},
body: String,
tag: {type: String, enum:['POLITICS', 'ECONOMY', 'EDUCATION']},
posted: {type: Date, default: Date.now},
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
PostModel.create(post);
res.json(post);
}
app.listen(3000);
If your schema and data you want to insert are matched then it should work.
Try below code. instead of PostModel.create(post);
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/nnnnnn', function (err) {
if (!err) {
console.log('connection successful');
} else {
console.log(err)
}
});
var PostSchema = mongoose.Schema({
title: { type: String, required: true },
body: String,
tag: { type: String, enum: ['POLITICS', 'ECONOMY', 'EDUCATION'] },
posted: { type: Date, default: Date.now },
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
// static data
var post = {
title: 'asdfasdf',
body: 'asdfasdfasdfasdf',
tag: 'POLITICS',
posted: new Date()
}
var postModel = new PostModel(post);
postModel.save(function (err, data) {
if (err) {
console.log('Error', err);
} else {
console.log('data inserted');
}
});
res.json(post);
}
app.listen(3000);
Instead of below line
mongoose.connect('mongodb://localhost/blogfall2016');
Try this one to make sure that database created successfully first,
then do your operation
mongoose.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

Resources