MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 - javascript

I used mongoose to connect my database to my app.
I got this unexpected error.
My app.js look like this
const express = require('express');
const mongoose = require('mongoose');
const authRoutes = require('./routes/authRoutes');
const cookieParser = require('cookie-parser');
const { requireAuth, checkUser } = require('./middleware/authMiddleware');
const run = require('./admin/connection');
const app = express();
// middleware
app.use(express.static('public'));
app.use(express.json());
app.use(cookieParser());
const {default : AdminBro} = require('admin-bro');
const buildAdminRouter = require('./admin/admin.router');
const options = require('./admin/admin.options');
const port = 3000;
const url = 'mongodb://localhost:27017/dbName';
let mongooseDb;
const databaseConnect = async () => {
mongooseDb = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true })
.then((result) => app.listen(3000))
.catch((err) => console.log(err));
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("we are connected to database");
});
const admin = new AdminBro(options)
const router = buildAdminRouter(admin);
app.use(admin.options.rootPath, router);
};
databaseConnect();
I already installed mongodb database.
I already find similar question in stackoverflow but that answers didn't resolve my issue. Any help will be appreciated. Thanks

If It's MAC OS, run following command and try again:
brew services restart mongodb-community
the commands that follow will be the following:
Stopping mongodb-community... (might take a while)
==> Successfully stopped mongodb-community (label: homebrew.mxcl.mongodb-community)
==> Successfully started mongodb-community (label: homebrew.mxcl.mongodb-community)

I faced a similar problem.Give a try to this one:
Open your C drive.
Make a folder named 'data'.
Make another folder inside this data folder name 'db'.
You can see in the documentation that By default MongoDB try to search these directories, We have to create these manually

This error occurs when you run your node app without a server.
Fix is to run your mongodb server first then your app.

Related

Error: Cannot find module './keys_dev' Require stack

I have cloned a GitHub repo for reference. But i don't know what this .keys_dev refers to. Everything seems fine to me. But it is returning me error. Everything is in its place as expected. I hope anyone can help me. It requires stack that is unknown to me. It is requiring api that is already defined. I need to understand can anyone help?
const express = require("express");
const bodyPaser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const path = require('path');
const cors = require('cors');
const users = require('./routes/api/users');
const level = require('./routes/api/levels');
const employee = require('./routes/api/employees');
const exception = require('./routes/api/exception');
const payslip = require('./routes/api/payslip');
const dashboard = require('./routes/api/dashboard');
const individualcost = require('./routes/api/individualcost');
const oneoffpayment = require('./routes/api/oneoffpayment');
const record = require('./routes/api/record');
const app = express();
//Body parser middleware
app.use(bodyPaser.urlencoded({ extended: false }));
app.use(bodyPaser.json());
app.use(cors())
//Db
const db = require("./config/keys").mongoURI;
//MongoDB connection
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport Middleware
app.use(passport.initialize());
//Passport config
require('./config/passport')(passport);
//Use routes
app.use('/api/users', users);
app.use('/api/level', level);
app.use('/api/employee', employee);
app.use('/api/exception', exception);
app.use('/api/payslip', payslip);
app.use('/api/dashboard', dashboard);
app.use('/api/individualcost', individualcost);
app.use('/api/oneoffpayment', oneoffpayment);
app.use('/api/record', record);
// Server static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App is running on port ${PORT}`));
const db = require("./config/keys").mongoURI;
This require is fetching application configurations from the local filesystem, in this case the db URI. Perhaps the author of the repo forgot to mention that detail? It's very likely that if you want to use a MongoDB you'll have to setup your own local or cloud database and create a file under config/keys that contains a mongoURI. This should look similar to this:
// this is the contents of ./config/keys
export default {
mongoURI: "mongodb+srv://project:your-mongo-uri-here",
};
If you're looking to start a mongo cluster on the cloud, I've been using cloud.mongodb for a small pet project, works like a charm and it has a free plan tier.
You can also run mongo locally and just point the mongoURI to your local mongo instance.

Error 404 when I make a request to the API in http://localhost:5000

I am carrying out a project in MERN Stack and when making the request to the Api it returns a 404 error.
I do not know what it can be since the server works correctly, the strange thing is that sometimes when lifting it if it works without touching anything but other times it does not and I do not know how to solve it.
Another curious fact is that when raising the servers of other projects that were working correctly, I get the same error.
Error on Google Chrome DevTools:
image of error in Google Chrome
Server:
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
require('dotenv').config()
const app = express()
const port = process.env.PORT || 5000
app.use(cors())
app.use(express.json())
mongoose
.connect('mongodb://127.0.0.1:27017/justwatch',{useNewUrlParser:true})
.catch(e=>console.log('Connection error:',e.message))
const connection = mongoose.connection
connection.once('open',()=>{
console.log('MongoDB MOVIES database connection successfully');
})
const movieRouter = require('./routes/movie')
const seriesRouter = require('./routes/serie')
app.use('/movies',movieRouter)
app.use('/series',seriesRouter)
app.listen(port,()=>{console.log(`Server is running on port: ${port}`)})
Router:
const router = require('express').Router()
let Movie = require('../models/movie.model')
router.route('/movies').get((req,res)=>{
let limite = parseInt(req.params.number)
Movie.find().limit(12)
.then(movies=>res.json(movies))
.catch(err=>res.status(400).json('Error: '+err))
})
router.route('/').get((req,res)=>{
Movie.find().limit(12)
.then(movies=>res.json(movies))
.catch(err=>res.status(400).json('Error: '+err))
})
module.exports = router
React requests:
const getMovies = async() => {
await axios.get('localhost:5000/movies/')
.then(res=>{ console.log(res.data); setMovies(res.data) })
.catch(err=>console.log(err)) console.log(movies) }

Cant connect to MongoDB in Firebase Functions

I am using Firebase Functions as the host for my MERN web app backend.
When I connect to MongoDB locally, it works and can run operations with the database. However, when I deployed to firebase functions, it failed to even connect to the database.
Code:
index.js
const functions = require('firebase-functions');
const server = require('./server.js');
exports.api = functions.runWith({ memory: "2GB", timeoutSeconds: 120 }).https.onRequest(server);
Part of server.js
const express = require("express");
const dotenv = require("dotenv");
const colors = require("colors");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const bodyParser = require("body-parser");
const routes = require("./routes/routes.js");
const mongooseMethods = require("./database.js");
dotenv.config({ path: "./config/config.env" });
mongooseMethods.connectDB(process.env.MONGO_URL);
const PORT = process.env.PORT || 8080;
// set up app
const app = express();
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
app.use(cors({ origin: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));
app.use("/api", routes); // /api routes
module.exports = app;
routes.js
const express = require("express");
const app = express.Router();
const testingApi = require('../controller/testing.js');
const authApi = require('../controller/auth.js');
// testing
app.get('/testing', testingApi.testing);
// user authentication
app.post('/user/register', authApi.createUser);
module.exports = app;
api/testing/ also works
database.js
const mongoose = require("mongoose");
const mongooseMethods = {
connectDB: async (url) => {
try {
console.log("Connecting to MongoDB")
const connection = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(`MongoDB Connected: ${connection.connection.host}`.cyan.bold);
return connection;
} catch (error) {
console.log(`Error: ${error.message}, Exiting`.red.bold);
process.exit(1);
}
}
}
module.exports = mongooseMethods;
auth.js
const User = require('../model/user.model.js');
const bcrypt = require("bcryptjs");
let authenticationApi = {
createUser: async (req, res) => {
try {
console.log("Creating");
let newUser = new User({
...req.body
})
let result = await newUser.save();
return res.status(200).json({ result: result });
} catch (error) {
return res.status(400);
}
}
}
module.exports = authenticationApi;
The error I received when sending request to firebase is
2020-02-27T02:34:46.334044912Z D api: Function execution took 30970 ms, finished with status: 'connection error'
Yet it runs perfectly fine in local. I also don't see the console log "connected to MongoDB". I'm guessing that the problem occurs in database.js that it failed to connect to mongo at the first place yet I don't know how to solve.
I am using the paid plan in Firebase and the outbound networking should be fine.
p.s. this is my first time posting here. thanks for your time and I apologize in advance if i'm breaking any rules.
Listening on a port is not a valid operation in cloud functions:
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
Cloud Functions listens for you, using the URL that it was assigned, then delivers the request to your code. When you pass your express app to onRequest(), that's all wired up for you.
I suggest starting with a stripped down, simplified version of an app just to gain experience about how things work, then add in more as you get comfortable.
The reason for this to happen is that the architecture of Firebase Functions is not an actual server, but a serverless lambda-like endpoint. Since it cannot establish a lasting connection to the database, that it has to make a connection every time it received a request, the database sees this as spam and shut down further connection request from Firebase.
Therefore, you simply cannot host a complete express app with intended lasting connection in Firebase Functions.
More on that in this article

mongodb : TableRow.TableRow is not a constructor

I am getting-started with mongodb.
I have set-up all the mongodb and the mongoose configuration and they work perfectly.
Here are the project files:
server.js:
const TableRow = require('./models/tableRow');
const bodyParser = require('body-parser');
const cors = require('cors')
const express = require('express');
const mongoose= require('mongoose')
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/table', function(err) {
if (err) { throw err; }
console.log('Successfully connected');
});
const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', () => {
console.log('MongoDB database connection established successfully!');
});
app.use('/', router);
router.route('/table/add').post((req, res) => {
let tableRow = new TableRow (req.body);
tableRow.save()
.then(issue => {
res.status(200).json({'tableRow': 'Added successfully'});
})
.catch(err => {
res.status(400).send('Failed to create new record');
});
});
app.listen(5757, () => console.log(`Express server running on port 5757`));
tableRow.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let TableRow = new Schema({
column1Data: {
type: String
},
column2Data: {
type: String
}
});
export default mongoose.model('TableRow', TableRow);
When I tried testing this with POSTMAN:
I get this error:
TypeError: TableRow is not a constructor
I think the problem is with the way I required the model in server.js:
const TableRow = require('./models/tableRow');
Someone else faced a similar issue and posted it on stackOverFlow. However, they are defining the model in the same file the server code.
Similar issue but doesn't solve my problem
So his post doesn't solve my issue.
Any idea how I can fix this?
Change from
export default mongoose.model('TableRow', TableRow);
To this:
module.exports = mongoose.model('TableRow', TableRow);
And import so: const TableRow = require('./models/tableRow');
It's CommonJS module specification which is the standard used in Node.js for working with modules (more info).
When using Node.js, including express framework, you should do it so.
module.exports is the object that's actually returned as the result of a require call.(Reference)
Remember:
You must use both import and export syntax from the same standard.
A brief summary of two module systems:
Today there are two module systems that are actively being used. CommonJS (CJS) is what Node.js has used historically. ESM (EcmaScript modules) is a newer system which has been added to the JavaScript specification. Browsers already support ES modules, and Node is adding support. (source)

cannot connect to mongo local DB from Node JS

I am learning Mongo DB, Mongoose and Node JS and I can't seem to connect my Node JS to local Mongo DB.
Here is my code:
dbtest.js
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
var Todo = mongoose.model('Todo', {
text : String
}, 'test');
var status = {
"status": "not connected"
};
app.get('/api/todos', function(req, res) {
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
{
if (err) {
res.json(status);
} else {
res.json('Connected');
}
});
});
app.listen(8080);
console.log("App listening on port 8080");
When I call api/todos GET request, the status JSON object is returned, meaning I cannot connect to the database.
I installed MongoDB Enterprise Server 3.14.10 completely and have it running but I don't know why my NodeJS application cannot connect.
Any suggestions are appreciated.
Your first mongoose.connect() argument lacks username / password combination:
mongoose.connect('mongodb://username:password#127.0.0.1:27017/exampleDB');
Try to connect db first before doing any action. Once it connected try to use inside your custom function. Below code will helps you to test local database
const express = require('express');
const app = express();
const port = 3000;
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/dbname', { useMongoClient: true });
mongoose.connection.on('connected', () => {
console.log('Connected to database ');
});
mongoose.connection.on('error', (err) => {
console.log('Database error: '+err);
});
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
Check your cmd window to see console.
For connecting to a local mongodb, you can use this URI, replacing USER, PASSWORD are DB with your values :
mongodb://USER:PASSWORD#127.0.0.1/DB?authSource=admin
You don't need to provide the port 27017, because it's the default one for mongodb.
The trick here is to add with 'authSource=admin' for enabling the authentication.
Documentation :
https://docs.mongodb.com/manual/reference/connection-string/#examples

Categories

Resources