Unable to connect with Mongoose (Mongodb) - reactjs

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.

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

Unhandled rejection: Data is not getting inserted into Mongodb

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

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

React-Native Firebase Deploy Error command Cli

Hi everyone i try to pass some images to my firebase with Functions but when i deploy firebase(with cli firebase deploy)inside my terminal i got an error and the deploy abort.
Apparently the error say my require inside function/index.js is not a function (line 9 col 45) but the gcconfig was do with the right method for me.
I want to correctly deploy firebase from CLI.
The error from cli firebase deploy i got on my terminal:
Error: Error occurred while parsing your function triggers.
TypeError: require(...) is not a function
at Object.<anonymous> (/Users/luca/Code/Code_Taff/Benibla/bnblproto/functions/index.js:9:45)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:15:15
at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:53:3)
function/index.js:
const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
const fs = require('fs');
const UUID = require("uuid-v4");
const gcconfig = {
projectId: "beniblaproto",
keyFilename: "beniblaproto.json"
};
const gcs = require("#google-cloud/storage")(gcconfig);
exports.storeImage = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
const body = JSON.parse(request.body);
fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
console.log(err);
return response.status(500).json({error: err});
});
const bucket = gcs.bucket("beniblaproto.appspot.com");
const uuid = UUID();
return bucket.upload(
"/tmp/uploaded-image.jpg",
{
uploadType: "media",
destination: "/events/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "image.jpg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, file) => {
if (!err) {
response.status(201).json({
imageUrl: "https://firebasestorage.googleapis.con/v0/b" +
bucket.name +
"/o/" +
encodeURIComponent(file.name) +
"?alt=media&token=" +
uuid
});
} else {
console.log(err);
response.status(500).json({error: err});
}
}
);
});
});
if someone can explain me where and for what i fail.
Thank you all have a good day
Firstly you need to import {Storage} of library;
const {Storage} = require("#google-cloud/storage");
after that you need to take an instance with your configuration object;
const gcs = new Storage(gcconfig);

No data returned on MongoDB using Express router

I have a Mongo database set up on a Bitnami Lightsail MEAN stack instance that I am trying to connect to with an Angular/Node/Express application that I am building. I have followed the instructions on how to connect and create SSH Port Forwarding from my local machine (https://docs.bitnami.com/aws/infrastructure/mean/).
I am able access localhost:8888, which gives me access to RockMongo that was set up on the MEAN Lightsail instance with my Mongo database. That being said, I think the configuration for the connection to the server from my local machine is fine.
When I run node server and navigate to the URL (http://localhost:3000/api/numbers) for my api GET method, I am not receiving an error on connecting to the database. Instead, I get the following response, which is basically an empty array of data:
{"status":200,"data":[],"message":null}
Here is the code for my api.js file:
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
// Connect
const connection = (closure) => {
return MongoClient.connect('mongodb://localhost:27017/sakDB', (err, db) => {
if (err) {
return console.log(err);
}
closure(db);
});
};
// Error handling
const sendError = (err, res) => {
response.status = 501;
response.message = typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
// Response handling
let response = {
status: 200,
data: [],
message: null
};
// Get numbers
router.get('/numbers', (req, res) => {
connection((db) => {
db.collection('numbers')
.find()
.toArray()
.then((numbers) => {
response.data = numbers;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
module.exports = router;
And the code for my router.js file:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
const api = require('./server/routes/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
I am beginning to think that this is some configuration issue with MongoDB on the MEAN Lightsail instance. If I try to run db.numbers.find() in MongoDB shell, I get the following error:
MongoDB server version: 3.4.7
> db.numbers.find()
Error: error: {
"ok" : 0,
"errmsg" : "not authorized on sakDB to execute command { find: \"numbers\", filter: {} }",
"code" : 13,
"codeName" : "Unauthorized"
}
I have to log in as a user mongo sakDB -u admin -p that I created to in order to find data on the collection.
When I try adding those credentials to the connection string mongodb://admin:PASSWORD#localhost:27017/sakDB, I receive a different authentication error:
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
It looks like this issue was related to Bitnami's server configuration with my Express application. It has been resolved.

Resources