Unhandled rejection: Data is not getting inserted into Mongodb - reactjs

Server is starting at 8080
GET / 304 - - 1.952 ms
(node:6139) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: bad auth Authentication failed.
at new MongooseServerSelectionError (/Users/abc/Desktop/success/node_modules/mongoose/lib/error/serverSelection.js:22:11)
at NativeConnection.Connection.openUri (/Users/abc/Desktop/success/node_modules/mongoose/lib/connection.js:808:32)
at Mongoose.connect (/Users/abc/Desktop/success/node_modules/mongoose/lib/index.js:333:15)
at Object. (/Users/abc/Desktop/success/pages/server.js:18:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:6139) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6139) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
GET / 304 - - 0.320 ms
GET / 304 - - 0.236 ms
GET / 304 - - 0.210 ms
When I run Port 8080 for my serverjs, the file works but no data gets into my mongoDB and I get the above error on my terminal. I only have a server.js page and an index.tsx page. My index.tsx page has a simple Hello world and I am trying to connect Mongodb using the server.js file.
Here is my code:
import express from 'express';
import { connect, connection, Schema as _Schema, model } from 'mongoose';
import morgan from 'morgan';
import path from 'path';
const app = express();
const PORT = process.env.PORT || 8080;
//Success
const MONGODB_URI = 'mongodb+srv://xxxxxxxxxx';
mongoose.connect(MONGODB_URI || 'mongodb://localhost/success', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
})
//Schema
const Schema = _Schema;
const BlogPostSchema = new Schema({
title: String,
body: String,
date: {
type: String,
default: Date.now()
}
});
//Model
const BlogPost = model('BlogPost', BlogPostSchema);
//Saving data to our mongoDB
const data = {
title: 'welcome',
body: 'first post'
};
const newBlogPost = new BlogPost(data);
newBlogPost.save((error) => {
if (error) {
console.log("Somethign happened");
} else {
console.log("data saved");
}
});
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));

I think it's because mongoose.connect is asynchronous(not very clear from the documentation). Try putting your code within the "connected" event and see if it works:
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
//Schema
const Schema = _Schema;
const BlogPostSchema = new Schema({
title: String,
body: String,
date: {
type: String,
default: Date.now()
}
});
//Model
const BlogPost = model('BlogPost', BlogPostSchema);
//Saving data to our mongoDB
const data = {
title: 'welcome',
body: 'first post'
};
const newBlogPost = new BlogPost(data);
newBlogPost.save((error) => {
if (error) {
console.log("Somethign happened");
} else {
console.log("data saved");
}
});
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
})

Related

Cannot connect correctly with Nodemon, attempting to connect with mongoDB

Attempting to run backend section of a project, and when I go to my localHost 5000 it says Server Is Ready, but when I try the path http://localhost:5000/api/users/ or http://localhost:5000/api/users/seed it says Cannot GET /api/users/. In my terminal, here's the code it throws.
[nodemon] starting `node --experimental-modules backend/server.js`
Serve at http://localhost:5000
(node:3612) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED
127.0.0.1:27017
at NativeConnection.Connection.openUri
(C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\connection.js:845:32)
at C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\index.js:345:10
at C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\helpers\promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\index.js:1135:10) at Mongoose.connect (C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\index.js:344:20)
at file:///C:/Users/lumpy/Desktop/aaaaa/backend/server.js:7:10
at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
at async Loader.import (internal/modules/esm/loader.js:166:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3612) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block, or by rejecting a promise which
was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the
CLI flag `--unhandled-rejections=strict` (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3612) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,
promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Both users and products are in the same folder, and while it can access and display the products fine, it cannot display the users. Before I noticed this, I was attempting to connect it to Mongo Compass, but it read "connect ECONNREFUSED 127.0.0.1:27017"
I never know what code to put up that's relevant, but here's the rest of my code.
userModel
import mongoose from 'mongoose';
const userSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, default: false, required: true }
},
{
timestamps: true,
}
);
const User = mongoose.model('User', userSchema);
export default User;
userRouter
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import data from '../data.js';
import User from '../models/userModel.js';
const userRouter = express.Router();
userRouter.get(
'/seed',
expressAsyncHandler(async (req, res) => {
const createdUsers = await User.insertMany(data.users);
res.send({ createdUsers });
})
);
export default userRouter;
server.js
import express from 'express';
import mongoose from 'mongoose';
import data from './data.js';
import userRouter from './routers/userRouter.js';
const app = express();
mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/aaaaa', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
app.get('/api/products/:id', (req, res) => {
const product = data.products.find((x) => x._id === req.params.id);
if (product) {
res.send(product);
} else {
res.status(404).send({ message: 'Product Not Found, gat dammit' });
}
});
app.get('/api/products', (req, res) => {
res.send(data.products);
});
app.use('/api/users', userRouter);
app.get('/', (req, res) => {
res.send('Server is ready');
});
app.use((err, req, res, next) => {
res.status(500).send({ message: err.message });
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serve at http://localhost:${port}`);
});
Mongoose connection is an async function, for which you need to use async await. try using:
(async() => {
await mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/aaaaa', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
})();
in your server.js file
In server.js after importing userRouter try adding
dotenv.config();

Unable to connect with Mongoose (Mongodb)

const express=require('express');
const mongoose=require('mongoose');
const morgan=require('morgan');
const path=require('path');
const app = express();
const PORT = process.env.PORT || 8080;
mongoose.connect('mongodb://localhost/SUCCESS', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
})
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
node pages/server.js
Server is starting at 8080
(node:6253) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at new MongooseServerSelectionError (/Users/Abc/Desktop/success/node_modules/mongoose/lib/error/serverSelection.js:22:11)
at NativeConnection.Connection.openUri (/Users/Abc/Desktop/success/node_modules/mongoose/lib/connection.js:808:32)
at Mongoose.connect (/Users/Abc/Desktop/success/node_modules/mongoose/lib/index.js:333:15)
at Object.<anonymous> (/Users/Abc/Desktop/success/pages/server.js:18:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:6253) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6253) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I had the same issue. Please update your code like this.
mongoose.connect("mongodb://127.0.0.1:27017/SUCCESS",{
useCreateIndex:true,
useNewUrlParser: true,
useUnifiedTopology: true}).then(()=> {
console.log('Database Successfully Connected')},error =>{
console.log(error)})
As next step,
Go to your Task Manager
Services
Start 'MongoDB'
Hope this will work.
// Seems like you did not define the default port of mangoose, Please refer below code
const mongoose = require('mongoose');
const db = "mongodb://localhost:27017/SUCCESS";
mongoose.connect(db, {
useCreateIndex:true,
useUnifiedTopology:true,
useNewUrlParser:true
}).then( () => {
console.log("Connected To Mongo Db DataBase");
}).catch((err) => {
console.log("DataBase Connection Error " + err);
})
I know I'm super late but this should fix it.
const db = mongoose.connect("mongodb://localhost/swag-shop",
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
}).then(() => {
console.log("Connected To Mongo Db DataBase");
}).catch((err) => {
console.log("DataBase Connection Error " + err);
});
then go to your powershell in windows or terminal in mac and type 'Mongod' and then create another tab in your terminal or open a another window of powershell and then type 'Mongo' and this should fix your problem.

Error: "Request failed with status code 500" while posting to API firebase

Error: "Request failed with status code 500" while posting to API
Until here i was getting cross origin error now when i added app.use(cors()) getting internal error 500
Made the below things to my code
const express=require('express')
const app=express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.use(cors());
app.post("/project",(req,res)=>cors(req,res,()=>{
const newProject={
title:req.body.title,
description:req.body.description,
status:req.body.status,
startdate:req.body.startdate,
enddate:req.body.enddate,
supervisor:req.body.supervisor,
createdAt:admin.firestore.Timestamp.fromDate(new Date())
}
admin.firestore().collection("Projects")
.add(newProject)
.then(doc=>{
return res.json({message:`Project ${doc.id} created successfully`})
})
.catch(err=>{
res.status(500).json({error:`Something went wrong, ${err}`})
})
}))
Below is the client side code :
const newProject=JSON.stringify({
title:project.name,
description:"",
status:project.status,
startdate:project.startdate,
enddate:project.enddate,
supervisor:project.supervisor,
})
axios.post("https://us-central1-flair-d7b59.cloudfunctions.net/api/project",newProject)
.then(res=>{
this.setState({ open: false });
Swal.fire({
icon:"success",
toast:true,
title: res,
position: 'top-end',
showConfirmButton: false,
showClass: {
popup: ''
},
timer: 2500
})
})
.catch(err=>{
console.log(err)
this.setState({loading:false})
Swal.fire({
icon:"error",
toast:true,
title:"Something went wrong, Please try again",
position: 'top-end',
showConfirmButton: false,
showClass: {
popup: ''
},
timer: 2500
})
})
tried a lot but no solution. Thank you
I'd recommend making use of the cors middleware to handle CORS handshaking rather than do it manually.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
to
app.use(cors());
You also don't parse the request's body as JSON before trying to use it. This can be achieved using the body-parser middleware. Because you are responding in JSON, I also assume you are sending your data as JSON.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const cors = require('cors');
const jsonBodyParser = require('body-parser').json();
admin.initializeApp();
const app = express();
app.use(cors()); // enable all origins
app.post("/project", (req,res) => {
jsonBodyParser(req, res, (err) => { // parse body as JSON
if (err) { // don't forget to handle errors when chaining to `next()` manually
res.status(500).json({error:'Failed to parse body as JSON'});
return;
}
const newProject= {
title: req.body.title,
description: req.body.description,
status: req.body.status,
startdate: req.body.startdate,
enddate: req.body.enddate,
supervisor: req.body.supervisor,
createdAt: admin.firestore.Timestamp.fromDate(new Date())
}
admin.firestore().collection("Projects")
.add(newProject)
.then(doc => {
return res.json({message:`Project ${doc.id} created successfully`})
})
.catch(err => {
res.status(500).json({error:`Something went wrong, ${err}`})
});
});
});
exports.app = functions.https.onRequest(app);

How to fix pending issue regarding mongoose with axios post

I'm working on a person project that requires data from a redux form to be sent to an express server through an axios call. I've got the data from the client to the server by using body-parser but am having problems saving to the MongoDB using mongoose. Why am I getting a pending request on my post call?
<code>
// Client side axios post call
export const createSchedule = formValues => async (dispatch, getState) => {
const res = await axios.post("/schedule/create", {
data: {
userId: getState().auth.googleId,
title: formValues.title,
description: formValues.description
}
});
dispatch({ type: CREATE_SCHEDULE, payload: res });
};
</code>
<code>
// server side axios post call
module.exports = app => {
app.post("/schedule/create", async (req, res) => {
const schedule = new Schedule({
googleId: req.body.data.userId,
title: req.body.data.title,
description: req.body.data.description
}).save(function(err) {
if (err) console.log("saved failed.");
else console.log("saved");
});
done(null, schedule);
});
};
</code>
<code>
// Schedule schema for mongoose
const mongoose = require("mongoose");
const { Schema } = mongoose;
const scheduleSchema = new Schema(
{
googleId: String,
title: String,
description: String,
date: { type: Date, default: Date.now }
},
{ collection: "schedules" }
);
mongoose.model("schedules", scheduleSchema);
</code>
Pending results in client console
TypeError: Schedule is not a constructor error in server console.
It worked out by changing how I accessed the Schedule model in my api call. I previously had imported it locally instead of using the mongoose.model("schedules") line that I should've used.

MEAN: TypeError: ... is not a constructor

I'm very new to development and working my way through this MEAN tutorial:
MEAN Stack Front To Back [Part 3] - User Model & Register
I've read a few questions on here but can't find a relevant answer.
Here is the primary error code:
Server started on port 3000
Database Error MongoError: failed to connect to server [localhost:27017]
on first connect
TypeError: User is not a constructor
at router.post (/Users/user/Desktop/Development/meanauthapp/routes/users.js:12:16)
Which is odd, because my mongod terminal states this:
2017-03-15T09:52:49.306-0700 I NETWORK
[thread1] waiting for connections on port 27017
2017-03-15T09:52:54.514-0700 I NETWORK
[thread1] connection accepted from 127.0.0.1:49188 #1 (1 connection now open)
2017-03-15T09:52:54.515-0700 I NETWORK
[conn1] received client metadata from 127.0.0.1:49188 conn1:
{ application: { name: "MongoDB Shell" },
driver: { name: "MongoDB Internal Client", version: "3.4.1" },
os: { type: "Darwin", name: "Mac OS X", architecture: "x86_64", version: "15.6.0" } }
/routes/users.js
/*---------------Dependencies-------------*/
const express = require('express');
const router = express.Router();
const User = require('../config/database');
const passport = require('passport')
const jwt = require('jsonwebtoken');
/*----------------------------------------*/
/*---------------Register-----------------*/
router.post('/register', (req, res, next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err) {
res.json({success: false, msg:'Failed to register user'});
} else {
res.json({success: true, msg: 'User Registered'})
}
});
});
/*----------------------------------------*/
/*---------------Authenticate---------------*/
router.post('/authenticate', (req, res, next) => {
res.send('AUTHENTICATE')
});
/*----------------------------------------*/
/*-----------------Profile------------------*/
router.get('/profile', (req, res, next) => {
res.send('PROFILE')
});
/*----------------------------------------*/
module.exports = router;
The line with error is : let newUser = new User({
/config/database.js
module.exports = { database: "mongodb://localhost:27017/famjam",
secret : "yoursecret" }
/models/users.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../models/database');
/*User Scheme*/
const UserScheme = mongoose.Scheme({
name: {
type: String
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
const User = module.exports = mongoose.model('User', UserScheme);
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
module.exports.getUserbyUsername = function(username, callback) {
const query = {username: username}
User.findOne(query, callback);
}
module.exports.addUser = function(newUser, callback) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
})
});
}
app.js
/*---------------Dependencies-------------*/
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const users = require('./routes/users')
const config = require('./config/database')
/*----------------------------------------*/
/*---------------Database-------------*/
mongoose.connect(config.database);
mongoose.connection.on('connected', () => {
console.log('connected to database ' +config.database)
});
mongoose.connection.on('error', (err) => {
console.log('Database Error '+err)
});
/*----------------------------------------*/
/*------------------App-------------------*/
const app = express();
// Port Number
const port = 3000;
app.listen(port, () => {
console.log('Server started on port '+port)
});
//CORS Middleware
app.use(cors());
// Body Parser Middelware
app.use(bodyParser.json())
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users)
/*----------------------------------------*/
/*---------------Index Route--------------*/
app.get('/', (req, res) => {
res.send('Invalid Endpoint')
});
app.get('/myaccount', (req,res) =>{
res.render('myaccount')
})
If your req.body is an object having name, email, username and password set, you should be able to create a new User simply doing:
let newUser = new User(req.body);
You get this error since you are passing to the constructor an object having 4 different attributes, while it expect to receive a request body.

Resources