Node/Express app hangs whenever interfacing with MongoDB, no errors given - node.js

I'm trying to create a CRUD REST API in NodeJS, Express, and Mongodb.
I did something to break all my routes where they no longer return responses. No errors, nothing in the console, etc. I'm not sure what happened, I had it working before. Through just some console.logs I figured out it was freezing whenever it interfaced with the database.
Now, when I send a post request in Postman, it just hangs with 'Loading request'. I'm sending my request as a raw JSON in the body and a content type of application/json; charset=UTF-8 in the header.
{"username":"zezimaUsername","rsn":"Zezima","avatar":"http://secure.runescape.com/m=avatar-rs/Zezima/chat.png"}
They seem to all be hanging once they interact with Mongodb. I have Mongodb running locally with the mongod --port 27017 and created my database with two collections (user and posts) in Mongodb Compass.
I setup my db in a db.js file...
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/my-group';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error: '));
module.exports = db;
And start my app with my server.js...
var express = require('express');
var api = require('./api');
var app = express();
app.use(express.json());
app.use('/api', api);
//Error handling, don't return stack trace to user, log in console.
app.use(function (err, req, res, next){
console.log(err.stack);
res.status(500).send('Something went wrong, internal server error.');
});
app.listen(3000, function(){
console.log("Listening on port 3000");
});
And define my routes in my api.js file...
var express = require('express');
var router = express.Router();
var User = require('./db/models/User');
var Post = require('./db/models/Post');
router.post('/register', function(req, res){
var user = new User(req.body);
user.save()
.then(function(item){
res.status(200).send({message: "User successfully created.", status: 200});
})
.catch(function(err){
res.status(400).send({message: "User failed to save to database", status: 400});
});
});
router.get('/user/:username', function(req, res){
var query = User.findOne({"username": req.params.username});
query.exec(function(err, user){
if(user === null){
res.status(404).send({message: "User not found", status: 404});
}else{
res.status(200).send(user);
}
});
});
router.post('/create_post', function(req, res){
var post = new Post(req.body);
post.save()
.then(function(item){
res.status(200).send({message: "Post successfully created.", status: 200});
})
.catch(function(err){
console.log(err);
res.status(400).send({message: "Post failed to save to database", status: 400});
});
});
router.get('/post/id/:id', function(req, res){
var query = Post.findOne({"_id":req.params.id});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
router.get('/post/boss/:boss', function(req, res){
var query = Post.find({"boss":req.params.boss});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
module.exports = router;
And just to be complete...my models look like...
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username:{
type: String,
required: true
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
posts:[{
type: Schema.Types.ObjectId,
ref: 'posts'
}]
});
var user = mongoose.model('users', userSchema);
module.exports = user;
and Post.js
var mongoose = require('mongoose');
var shortid = require('shortid');
var Schema = mongoose.Schema;
var postSchema = new Schema({
_id:{
type: String,
default: shortid.generate
},
username:{
type: Schema.Types.ObjectId,
ref: 'users'
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
boss:{
type: String,
required: true
}
});
var post = mongoose.model('posts', postSchema);
module.exports = post;
I'm not sure what's happening, I keep reading a bunch of various tutorials and the documentation but I'm just not seeing the issue I'm having.

You have not required your db.js file in your server.js file.
Require it after var express = require('express');
let db = require("./db");
Then it will work fine.

Related

not entering into save function in mongoose

I am newbie to node js and mongoose and unable to save the record in the mongoose I am using Mongodb atlas I have tried several ways to debug and tried different things but not getting save or not able enter into the inside the save function. so not able to handle the save callback in moongose If try to hit request in postman its not getting the response it getting blocked and not entering into save so Thanks in Advance
controller.js
const mongoose = require('mongoose');
const User = require('../models/users');
exports.registerUser = (req,res,next)=>{
console.log(req.body);
const user = new User({
_id:mongoose.Types.ObjectId(),
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
});
user.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
res.json({message: err});
}
else{
res.json({ message: 'User created' });
}
})
}
router.js
const mongoose = require('mongoose');
const User = require('../models/users');
exports.registerUser = (req,res,next)=>{
console.log(req.body);
const user = new User({
_id:mongoose.Types.ObjectId(),
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
});
user.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
res.json({message: err});
}
else{
res.json({ message: 'User created' });
}
})
}
model.js
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
firstName: {type: String, required: true},
lastName: {type: String, required: true},
email: {type: String, required: true}
});
module.exports = mongoose.model('User', userSchema);
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const userRoutes = require('./api/routes/users');
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<connection string>/admin";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
});
mongoose.Promise = global.Promise;
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use((req,res,next )=>{
console.log(req);
res.header("Access-Control-Allow-Origin", "*");
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
app.use('/', userRoutes);
app.use((req,res,next)=>{
const error = new Error('Not Found');
error.status = 404;
next(error);
});
app.use((error,req,res,next)=>{
res.status(error.status || 500);
res.json({
error:{
message: error.message
}
})
});
module.exports = app;
Are you sure mongoose is using any connections? Seems like you connected to server with mongodb module instead. See the Getting Started docs on how to connect with mongoose.

Unhandled promise Rejection (rejection id: 1) - Node.js

I'm new to Node.js and trying to figure out of some problems.
I've defined a signup function on a Node.js server for an Android app who writes user's info on MongoDB.
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/serverModel'),
bodyParser = require('body-parser');
var url = "mongodb://localhost:27017/ProjectDB";
mongoose.Promise = global.Promise;
mongoose.connect(url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/serverRoute');
routes(app);
app.listen(port);
console.log('Project RESTful API server started on: ' + port);
serverModel
var UserSchema = new mongoose.Schema({
userName: {type: String, unique: true, required: true},
email: {type: String, unique: true, required: true},
password: {type: String, required: true},
createdAt: {type: String, required: true}
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
serverRoute
module.exports = function(app) {
var Project = require('../controllers/serverController');
// Project Routes
app.route('/signup')
.post(Project.signup);
};
serverController
...
mongoose.Promise = global.Promise;
exports.signup = function(req, res) {
return new Promise( function(resolve,reject) {
var user = new User({
userName: req.body.name,
password: req.body.pass,
mail: req.body.email,
createdAt : new Date()
});
user.save()
.then(function() { resolve({ status: 201, message: 'User Registered Successfully !' })})
.catch(function(err) {
if (err.code == 11000) {
reject({ status: 409, message: 'User Already Registered !' });
} else {
reject({ status: 500, message: 'Internal Server Error !' });
}
});
})};
...
It compiles without any error.
When I try to send a JSON via Postman like this:
{
"userName" : "username",
"email" : "user.name#gmail.com",
"password" : "blabla1"
}
it reports
UnhandledPromiseRejectionWarning: Unhandled promise Rejection (rejection id: 1) [object Object]
I've read tons of posts but I can't get out of this.
Any help?
Thanks.
Try this and revert.
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/serverModel'),
bodyParser = require('body-parser');
var url = "mongodb://localhost:27017/ProjectDB";
mongoose.Promise = global.Promise;
mongoose.connect(url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/serverRoute');
//change
//routes(app);
app.use('/',routes);
app.listen(port);
console.log('Project RESTful API server started on: ' + port);
serverRoute
var express = require('express');
var router = express.Router();
// GET home page.
router.post('/signup', function(req, res, next) {
var Project = require('../controllers/serverController');
Project.signup().then(function(result){
res.send(result);
}).catch(function(err){
res.send(err);
});
});
module.exports = router;

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

Not able to save a model in mongoDB server with nodeJS

This is my Schema which is in models/adder folder:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
title: { type: String, required: true },
image: { type: String, required: true },
url: { type: String, required: true }
});
module.exports = mongoose.model('Product', schema);
Now this is my index.js where all the routes have been made for get, post and delete:
var express = require('express');
var router = express.Router();
var Product = require('../models/adder');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.createConnection('localhost:27017/replica');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('partials/index', { title: 'Express' });
});
router.get('/adder', function(req, res, next) {
res.render('adder/adder')
})
router.post('/added', function(req, res, next) {
var products = new Product({
title: req.body.title,
image: req.body.image,
url: req.body.url
});
products.save(function(err, done) {
if (err) {
console.log(err);
} else {
console.log('that have been saved')
}
res.redirect('/');
});
});
module.exports = router;
Now whenever i am submiting the fourm products have all the data i entered I had consoled it and i am able to make conenction with my local mongoDB server. But i am not able to use save function. Can anyone guide me how to save the data which is in products .

Validation failed nodejs required field

I am creating creating a bookstore demo app in Node.js. I have ran into a little situation with the POST request for creating a genre. I've setup so the name of the genre must be required if not don't insert it to the database. But when I use Postman to POST to the url localhost:3000/api/genres with the JSON
{
"name": "TEST"
}
It throws an error
{
"error": "Genre validation failed"
}
When I remove the required field in the genreSchema it works but the name of the genre doesn't appear. Here is my code
Code:
genre.js
var mongoose = require("mongoose");
// Create a schema for genre
var Schema = mongoose.Schema;
var genreSchema = Schema({
name:{
type: String,
required: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model("Genre", genreSchema);
// Methods
// get genres
module.exports.getGenres = function(callback, limit) {
Genre.find(callback).limit(limit);
};
// add a new genre
// TODO: Not working in Postman ValidationError
module.exports.addGenre = function(genre, callback) {
Genre.create(genre, callback);
};
app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Genre = require('./models/genre');
var Book = require('./models/book');
// Connect to mongoose
mongoose.connect("mongodb://localhost/bookstore");
var db = mongoose.connection;
app.get("/", function(req, res){
res.json({ error: "Please use /api/books or /api/genres" });
});
// GET /api/genres
app.get('/api/genres', function(req, res){
Genre.getGenres(function(err, genres){
if(err) {
res.json({error: err.message})
}
res.json(genres);
});
});
app.post('/api/genres', function(req, res){
var genre = req.body;
Genre.addGenre(genre, function(err, genre){
if(err) {
res.json({
error: err.message
})
}
res.json(genre);
});
});
// GET /api/books
app.get('/api/books', function(req, res){
Book.getBooks(function(err, books){
if(err) {
res.json({error: err.stack})
}
res.json(books);
});
});
// GET /api/book/:id
app.get('/api/book/:_id', function(req, res){
Book.getBookById(req.params._id, function(err, book){
if(err) {
res.json({error: err.message})
}
res.json(book);
});
});
app.listen(3000, function(){
console.log("Running on port 3000!")
});
Have you tried console.log(req.body); inside your post route? I don't think you've setup body-parser as middleware so req.body is coming in empty and therefore not sending anything to your Genre.addGenre method.

Resources