deprecation warning is getting while starting nodemon index.js in cli - node.js

getting an error like this
i am doing a simple node js project that connect with mongodb. how to resolve this issue.?
this is the error getting in the terminal
DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
listening to serve 8080
Could not connect to database: { MongoNetworkError: failed to connect to server [localhost:27017] on first connect
mongo connect(index.js)
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const config = require('./config/database');
mongoose.Promise = global.Promise;
mongoose.connect(config.uri, (err)=>{
if(err){
console.log('Could not connect to database: ', err);
}
else{
console.log('Connected to database: ' +config.db);
}
});
app.get('/', (req, res)=>{
res.send('<h1>hello world</h1>');
});
app.listen(8080, ()=>{
console.log('listening to serve 8080')
});
database.js in config folder
const crypto = require('crypto').randomBytes(256).toString('hex');
module.exports= {
uri: 'mongodb://localhost:27017/' + this.db,
secret:
'crypto',
db:
'login'
}
how to solve?

mongoose.connect(config.uri, {useNewUrlParser: true}, (err)=>{
if(err){
console.log('Could not connect to database: ', err);
}
else{
console.log('Connected to database: ' +config.db);
}
});
That should work, just needs an extra parameter

Related

NodeJS connection with MongoDB using Mongoose

I am trying to view mongodb collections (just to view) in browser URL by accessing localhost:4000/books
app.js code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Book = require("./book.model");
//mongo DB database connection: databse nmae is: example
var db = "mongodb://localhost:27017/example";
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
const conSuccess = mongoose.connection
conSuccess.once('open', _ => {
console.log('Database connected:', db)
})
conSuccess.on('error', err => {
console.error('connection error:', err)
})
var port = 4000;
app.listen(port, function () {
console.log("app listening on port " + port);
});
//REST get
app.get('/', function(req,res){
res.send("happy to be here");
});
//work on here localhost:4000 works but not localhost?4000/books
//get all "books" collections
app.get('/books', function(req,res) {
console.log("get all books");
Book.find({})
exec(function(err, books){
if(err){
res.send("error has occured");
} else {
console.log(books);
res.json(books);
}
});
});
book.model.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: String,
author: String,
category: String,
});
module.exports = mongoose.model("Book", BookSchema);
and the mongodb server started in cmd propt
ran> node app
console displayed messages as
"app listening on port 4000
Database connected: mongodb://localhost:27017/example"
in URL, when I tried to access like this
localhost:4000/books
display error as
reference error: exec is not defined. why is that, please help on this issue. I am working on rectify this erro for 3 days and really stcuk on this without moving forward.
use . before exec just try like this
app.get('/books', function(req,res) {
console.log("get all books");
Book.find({}).exec(function(err, books){
if(err){
res.send("error has occured");
} else {
console.log(books);
res.json(books);
}
});
});

nodemon app crashed - waiting for file changes

I am learning node.js on my own and I do not understand why I get that error "[nodemon] app crashed - waiting for file changes before starting..". I have the same code as the one on the tutorial. What can be wrong?
Thank you for your help!
const express = require('express');
const mysql = require('mysql');
//create connection
const db = mysql.createConnection({
host: 'localhost',
user : 'root',
password : '123456',
});
//connect
db.connect((err)=>{
if(err){
throw err;
}
console.log("mysql is CONNECTED");
});
const app = express();
app.get('/createdb',(req,res) =>{
let sql = 'CREATE DATABASE nodemysql';
db.query(sql,(err, result)=>{
if(err) throw err;
console.log(result);
res.send('database created');
})
})
app.get('/createdb',()=>{
console.log("server started on port 3000");
})
app.listen('3000',()=>{
console.log("server started on port 3000");
});
Make sure mysql is installed:
npm install mysql --save
Try console.error(err) followed by return:
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "example.org",
user: "bob",
password: "secret"
});
connection.connect(function(err) {
if (err) {
console.error("error connecting: " + err.stack);
return;
}
console.log("connected as id " + connection.threadId);
});

how to resolve - MongoError: failed to connect to server [zzzzz.mlab.com:xxxx] on first connect

I am trying to connect with my mlab database, but i'm getting the following MongoError.
MongoError: failed to connect to server [zzzzz.mlab.com:xxxx] on first
connect [MongoError: connect ETIMEDOUT xx.xx.xx.xxx.xxxxx
The following is my api.js file:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const post = require('../models/post');
const db = "mongodb://uname:pw#dsxxxxx.mlab.com:xxxxx/xxxxx";
mongoose.Promise = global.Promise; //we add this because if we dont, you may get a warning that mongoose's default promise library is deprecated
mongoose.connect(db, function(err) {
if(err) {
console.log('Connection error');
}
});
router.get('/posts', function(req, res) {
console.log('Requesting posts');
post.find({})
.exec(function(err, posts) {
if (err) {
console.log('Error getting the posts');
} else {
res.json(posts);
console.log(posts);
}
});
});
module.exports = router;
I have installed all the dependencies like mongoose. I'm not quite sure why i am getting this error.
I'd appreciate any guidance on this.
The error is as follows:
your database server seems unreachable, are you sure that credentials, IP, and port are correct ?

Refused connection to mLab database via MongoClient.connect() method

I am trying to create a very simple website. I have created a basic database on mLab and have setup a user with dbuser = folr and dbpassword = folr. However when trying to connect I get the error message:
{ [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }
Why is this happening?
const express = require('express')
const app = express()
const bodyParser= require('body-parser')
const MongoClient = require('mongodb').MongoClient
var db
MongoClient.connect('mongodb://folr:folr#ds047712.mlab.com:47712/familytimeline', function(err, database) {
if (err) return console.log(err)
db = database
app.listen(process.env.PORT || 3000, function() {
console.log('listening on 3000')
})
})
app.use(bodyParser.urlencoded({extended: true}))
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.post('/new', function(req, res) {
db.collection('quotes').save(req.body, function(err, result) {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
})

MongoError: socket hang up

I am trying to connect to the mongodb database on mongolabs(mlabs). I connect successfully when I run the code on my local computer and server.But When I run on my aws server I get this error database error { [MongoError: socket hang up] name: 'MongoError', message: 'socket hang up' }
Code trial.js:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var mongojs = require('mongojs');
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd'], { ssl : true });
db.on('error', function (err) {
console.log('database error', err);
});
db.on('connect', function () {
console.log('database connected');
});
db.mohd.find({}, function (err, docs) {
if(err){
console.log("error");
}else{
console.log(docs+"found");
}
});
app.set('view engine','ejs');
app.get('/',function(req,res){
console.log("hi");
});
app.listen(9000,function(){
console.log("server strated");
});
// catch 404 and forward to error handler
module.exports = app;
Got connection error on Amazon Web Service server but successful on local computer.
Ok so I solved the issue it was due to ssl connect method just removed it and was solved.
Use Instead:
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd']);

Resources