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
Related
I am trying to design an API using Snowflake and Nodejs. For that I am using the following things :
Express
ejs
snowflake-sdk (nodejs module)
I want to fetch data from snowflake and want to display it on my ejs webpage. Please help if anyone has fetched data and populated it on a webpage using nodejs and snowflake.
this is my server.js file
const express = require("express");
const app= express();
const sql = require("./snowflake");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true}));
app.set("view engine","ejs");
app.get("/", function(request,response){
response.render("index");
});
app.get("/request/:core", async function(request,response){
let core=await sql.getCore(request.params.core_name);
response.render("request",{request: core});
});
const http = require('http');
const port=3000;
const server=http.createServer(function(req,res){
})
const listener = app.listen(port,function(error){
if(error){
console.log("Something went wrong due :", error);
}
else{
console.log('Server is listening port '+port);
}
})
This is my database.js file. I am able to connect to snowflake and run queries but can't understand, how to fetch the query result on the ejs webpage.
const { initParams } = require('request');
const sql = require('snowflake-sdk');
const connection = sql.createConnection({
account: 'account_name',
authenticator: 'SNOWFLAKE',
username: 'username',
password: 'password',
database: 'database',
schema: 'schema'
});
module.exports.getCore = async() =>{
connection.execute({
sqlText: 'Select column from Table_name',
complete: async function(err,stmt,rows){
let pool= await sql.connect();
return rows;
}
})
}
There is a sample application that you can try to compare, is written on node.js. It is a Citi Bike dashboard that lets users view bike usage over time and in differing weather conditions. The source code is available on GitHub.
More details: https://quickstarts.snowflake.com/guide/data_app/#4
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
I am actually involved in a POC and looking to build a web app which can display SQL results after hitting a button. Got to know that seriate node.js is a good platform for this. But unable to find out how to link these components. Any help towards this would be appreciable.
You can check the below code
var webconfig = {
user: 'login',
password: 'sa#123',
server: 'localhost',
database: 'TestDB',
options: {
encrypt: false // Use this if you're on Windows Azure
}
}
var express = require('express');
var sql = require('mssql');
var http = require('http');
var app = express();
var port = process.env.PORT || 8000;
var connection = new sql.Connection(webconfig, function(err) {
var request = new sql.Request(connection);
request.query('select * from Users', function(err, recordset) {
if(err) // ... error checks
console.log('Database connection error');
console.dir("User Data: "+recordset);
});
});
app.listen(port);
console.log(port+' is the magic port');
I made this node js app and then i tried with postman but every time i made a request that involves mongodb, it keeps loading. The function find of the model is where the code stops and the callback is never called.
app.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
mongoose = require('mongoose');
//Connection to DB
mongoose.connect('mongodb://localhost:27017/users', function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var models = require('./models/user')(app, mongoose);
var userContoller = require('./controllers/user');
var router = express.Router();
router.get('/', function(req, res) {
console.log('GET');
res.send("Hello World!");
});
app.use(router);
var users = express.Router();
users.route('/users')
.get(userContoller.findAllUsers);
app.use('/api', users);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
models/user.js
exports = module.exports = function(app, mongoose){
var userSchema = new mongoose.Schema({
userName: { type: String },
password: { type: Number }
});
mongoose.model('User', userSchema);
};
controllers/user.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
//GET - Return all tvshows in the DB
exports.findAllUsers = function(req, res) {
console.log('llega');
User.find(function(err, users) {
if(err) res.send(500, err.message);
console.log('GET /users')
res.status(200).jsonp(users);
});
};
The mongodb server is started through the console but i don't know how to check it.
Thanks!
EDIT:
I made the code easier for me to test and solve the problem.
The code now is this and im not getting the connection to mongodb.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', function() {
console.log('error');
});
db.once('open', function() {
console.log('connected');
});
I don't get in the console the error or the connected.
In the mongod console i get some messages saying that a new connection was made. This happens every time i open the nodejs program.
Thanks
I think the problem is that you are giving call back to the mongoose.connect function. In my case i did:
mongoose.connect(url, options)
const db = mongoose.connection
db.on('error', function () { console.log('Cannot Connect to DB') })
db.once('open', function () { console.log('Mongoose Connected to DB') })
Also instead of:
users.route('/users').get(userContoller.findAllUsers);
You may try:
users.get('/users', userController.findAllUsers);
And I realized that you don't pass a next argument to your controller which express generally complains if you dont pass.
Edit: I think i found the error.
When you are using the .find function you need to pass 2 arguments. In your case because you are not passing the callback as the second argument it never gets called.
User.find({}, callback) should do it.
I found the problem.
The version of mongoose was older than the needed to connect to my mongodb version. Just update it via npm and good to go.
I am using node + redis and I facing strange issue when ever I run my app , connect event of redis client is called multiple times automatically as written in redis.js file.
Below is my code Server.js:
var express=require('express');
var app=express();
var port=8000;
var path = require('path');
var logger=require('morgan');
var bodyParser = require('body-parser');
var router = express.Router();
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.send({message:"Welcome to nodejs APIS"});
});
var redisObj=require('./redis.js');
app.use('/redischeck',redisObj);
app.listen(port,function(err,res){ if(err){ console.log("Server error");}else{console.log("Server running on port 8000");}});
redis.js
var express = require('express');
var router = express.Router();
var redis = require("redis");
var client = redis.createClient();
client.on('connect', function() {
console.log('connected'); // Prints multiple time in console
});
router.get('/', function(req, res) {
client.on("error", function (err) { console.log("Error " + err);});
client.set("foo", "bar", function (err, reply) {
client.quit();
res.json({status:'Success'});
});
});
module.exports=router;
I also cross checked this issue using 'netstat -na | grep 6379'.My observation were many connection were created and then went in to TIME_WAIT state which was strange because I just ran my app on my localhost without anyone connecting it from some other end.
Am I doing something wrong in code.
It was a mistake from my side I had changed timeout values in redis.conf file located at /etc/redis/redis.conf so that redis connection does not go in TIME_WAIT state for 60 sec.