Can't use and connect to MongoDB - javascript

So, I am building a small URL shortener project with js, express, and MongoDB but, I got errors when I'm trying to run my local server and I can't connect to MongoDB!
This is my code:
const express = require('express')
const mongoose = require('mongoose')
const ShortUrl = require('./models/shortUrl')
const app = express();
mongoose.connect('mongodb://localhost/urlShortener', {
useNewUrlParser: true, useUnifiedTopology: true
})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false}))
app.get('/', async (req, res) => {
const shortUrls = await ShortUrl.find()
res.render('index', { shortUrls: shortUrls })
});
app.post('/shortUrls', async (req, res) => {
await ShortUrl.create({ full: req.body.fullUrl })
res.redirect('/')
})
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl })
if (shortUrl == null) return res.sendStatus(404)
shortUrl.clicks++
shortUrl.save()
res.redirect(shortUrl.full)
})
app.listen(process.env.PORT || 5000);
And this is the full log:
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:342:10
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:1176:10)
at Mongoose.connect (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:341:20)
at Object.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\server.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 1096791,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:381:20)
at Socket.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
Node.js v17.7.2
[nodemon] app crashed - waiting for file changes before starting...
Thank u guys =)
I was trying to start the small URL-shortener project that I wrote in js, express, and MongoDB but, the problem is that I can't connect to my MongoDB database :(

I solved the problem, so, I replaced localhost with 127.0.0.1 in the connection string and now my problem is solved!
it is because of some ipv6 configurations...
Thank u :)

Related

My post request req.body turns empty on Heroku

My post request to create new item, turns me with new item created. It is working well in localhost.
But when I deploy my app on heroku and then post request Status Code: 503 Service Unavailable , but empty res.body. Here also my server.js file
server.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const items = require("./routes/api/items");
const users = require("./routes/api/user");
const auth = require("./routes/api/auth");
app.use(express.json());
require("dotenv").config();
mongoose.connect(process.env.MONGO_DB).then(console.log("connected"));
app.use(cors());
app.use("/api/items", items);
app.use("/api/users", users);
app.use("/api/auth", auth);
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
const listener = app.listen(process.env.PORT || 5000, () => {
console.log("Your app is listening on port " + listener.address().port);
});
item.js
router.post("/createTeam", auth, (req, res) => {
const newItem = new Item({
name: req.body.name,
});
newItem.save(function (err, result) {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
itemActions.js
export const addItems = (input) => (dispatch, getState) => {
axios
.post("/api/items/createTeam", input, tokenConfig(getState))
.then((res) =>
dispatch({
type: ADD_ITEM,
payload: res.data,
})
)
.catch((err) =>
dispatch(
returnErrors(err.response.data, err.response.status, "GET_ERRORS")
)
);
};
Also my heroku logs are here when I create new Team
2021-12-04T09:51:55.743015+00:00 app[web.1]: MongoWriteConcernError: No write concern mode named 'majority\"' found in replica set configuration
2021-12-04T09:51:55.743023+00:00 app[web.1]: at MessageStream.messageHandler (/app/node_modules/mongodb/lib/cmap/connection.js:463:30)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at MessageStream.emit (events.js:400:28)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at processIncomingData (/app/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at MessageStream._write (/app/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
2021-12-04T09:51:55.743025+00:00 app[web.1]: at writeOrBuffer (internal/streams/writable.js:358:12)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at MessageStream.Writable.write (internal/streams/writable.js:303:10)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at TLSSocket.ondata (internal/streams/readable.js:731:22)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at TLSSocket.emit (events.js:400:28)
2021-12-04T09:51:55.743027+00:00 app[web.1]: at addChunk (internal/streams/readable.js:293:12)
2021-12-04T09:51:55.743027+00:00 app[web.1]: at readableAddChunk (internal/streams/readable.js:267:9) {
2021-12-04T09:51:55.743028+00:00 app[web.1]: code: 79,
2021-12-04T09:51:55.743030+00:00 app[web.1]: codeName: 'UnknownReplWriteConcern',
2021-12-04T09:51:55.743030+00:00 app[web.1]: errInfo: {
2021-12-04T09:51:55.743031+00:00 app[web.1]: writeConcern: { w: 'majority"', wtimeout: 0, provenance: 'clientSupplied' }
2021-12-04T09:51:55.743031+00:00 app[web.1]: },
2021-12-04T09:51:55.743032+00:00 app[web.1]: result: {
2021-12-04T09:51:55.743032+00:00 app[web.1]: n: 1,
2021-12-04T09:51:55.743032+00:00 app[web.1]: opTime: { ts: new Timestamp({ t: 1638611515, i: 13 }), t: 104 },
2021-12-04T09:51:55.743033+00:00 app[web.1]: electionId: new ObjectId("7fffffff0000000000000068"),
2021-12-04T09:51:55.743033+00:00 app[web.1]: ok: 1,
2021-12-04T09:51:55.743034+00:00 app[web.1]: writeConcernError: {
2021-12-04T09:51:55.743034+00:00 app[web.1]: code: 79,
2021-12-04T09:51:55.743034+00:00 app[web.1]: codeName: 'UnknownReplWriteConcern',
2021-12-04T09:51:55.743035+00:00 app[web.1]: errmsg: `No write concern mode named 'majority\\"' found in replica set configuration`,
2021-12-04T09:51:55.743035+00:00 app[web.1]: errInfo: [Object]
2021-12-04T09:51:55.743036+00:00 app[web.1]: },
2021-12-04T09:51:55.743036+00:00 app[web.1]: '$clusterTime': {
2021-12-04T09:51:55.743036+00:00 app[web.1]: clusterTime: new Timestamp({ t: 1638611515, i: 13 }),
2021-12-04T09:51:55.743036+00:00 app[web.1]: signature: [Object]
2021-12-04T09:51:55.743037+00:00 app[web.1]: },
2021-12-04T09:51:55.743037+00:00 app[web.1]: operationTime: new Timestamp({ t: 1638611515, i: 13 })
2021-12-04T09:51:55.743037+00:00 app[web.1]: }
2021-12-04T09:51:55.743037+00:00 app[web.1]: }
SOLUTION
I removed '' or "" from MONGO_DB which is on heroku config vars, and solved

Mysql Error - 1251 'ER_NOT_SUPPORTED_AUTH_MODE'

I know that this question was already answered in SO, but the suggested fixxes dont work for me!
Error:
throw err; // Rethrow non-MySQL errors
^
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
at Handshake.Sequence._packetToError (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:223:5)
at addChunk (_stream_readable.js:309:12)
--------------------
at Protocol._enqueue (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\Dev\Programmierung\FitnessAppExpo\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (C:\Dev\Programmierung\FitnessAppExpo\server\server.js:29:5)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11 {
code: 'ER_NOT_SUPPORTED_AUTH_MODE',
errno: 1251,
sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client',
sqlState: '08004',
fatal: true
}
I have a Xampp Server running with myphpadmin on localhost. I tried to insert this code in myphpadmin:
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY '';
But if I try to use this it gives me an error inside phpmyadmin:
Missing ',' before start of a new ALTER operation!
and a second one stating:
Unknown ALTER operation (near by)
Is there something special I need to do when I want to use or execute this command inside phpmyadmin? Because the way that the ALTER Query is written doesnt let me execute it..
Node (Express) Code:
var mysql = require("mysql");
var express = require("express");
var session = require("express-session");
var app = express();
var cors = require("cors");
var bodyParser = require("body-parser");
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
app.use(
session({
secret: "ssshhhhh",
saveUninitialized: true, // (default: true)
resave: true
})
);
app.use(cors({ origin: ["http://localhost:4200"], credentials: true }));
var con = mysql.createConnection({
host: "localhost",
// host: "127.0.0.1:3307",
user: "root",
password: "",
database: "fitness_app"
});
con.connect(err => {
if (err) throw err;
console.log("Database connected -> ");
});
var server = app.listen(8090, () => {
var host = "localhost";
var port = server.address().port;
console.log("App listening at http://%s:%s", host, port);
});
~Faded
Execute the following query in MYSQL Workbench
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Where root as your user localhost as your URL and password as your password
Then run this query to refresh privileges:
flush privileges;
Try connecting using node after you do so.
If that doesn't work, try it without #'localhost' part.

Connection to server keeps failing connect ETIMEDOUT 94.195.191.104:27017

Each time I try to connect to my server to access the documents in the database, it comes back with a connect ETIMEDOUT error.
I own the server, running Mongo 4.0, have run mongod and left running, there is data in the collection.
let MongoClient = require('mongodb').MongoClient;
let uri = "mongodb://notmyrealusername:notmyrealpassword#thomas.misson.info/tom-portfolio";
MongoClient.connect(uri, { useNewUrlParser: true }, async function(err, db) {
try{
if (err) throw err;
let res = await db.collection("projects").find().count()
console.log(res);
db.close();
}
catch(err)
{
console.log(err);
}
});
Error message:
{ MongoNetworkError: connect ETIMEDOUT 94.195.191.104:27017
at Socket.err (H:\Documents\Personal projects\node_modules\mongodb-core\lib\connection\connect.js:287:16)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
I have opened the port using netsh advfirewall firewall add rule name="Open mongod port 27017" dir=in action=allow protocol=TCP localport=27017
Have now added new interface to the mongod.cfg file.
# network interfaces net:
port: 27017
bindIp: 127.0.0.1, 94.195.191.104

Trouble making nodejs mysql connection

I am trying to make a simple connection between my nodejs server and my mysql db (using Microsoft SQL server manager studio v14), below is my code and the error message appearing in my console window.
here is my code:
var express = require('express');
var app = express();
var sql = require("mssql");
app.get('/', function (req, res) {
// config for your database
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Schools', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
The error I am getting looks like this:
Server is running..
tedious deprecated The default value for `options.encrypt` will change from `false` to `true`. Please pass `false` explicitly if you want to retain current behaviour. node_modules\mssql\lib\tedious.js:212:23
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:275:13)
at Connection.emit (events.js:182:13)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:14)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:30)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:174:19)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1299:37)
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1242:12)
at C:\Users\smr09\Desktop\Code\ou\db_test\test.js:24:17
at _poolCreate.then.catch.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:178:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
I am rather new at this particularly with dealing with databases. Can someone explain what the error means?
Add this line to the config:
options: {
encrypt: false
}
It will finally look like:
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX' ,
options: {
encrypt: false
}
};
try to put encrypt: false in your config{}, it will work.
your error:
ConnectionError: Failed to connect to localhost:1433 - Could not
connect (sequence)
My problem was resolved by adding port
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX',
port: '',
};

{ [Error: listen EADDRINUSE :::5000]

What's wrong with the following Server.JS file? We are trying to connect Deployd to Heroku and keep getting the following error. We're using Nitrous, and I have configure the mongoDB port to 5000. Any help is appreciated. Thanks a ton!
Server.JS
// require deployd
var deployd = require('deployd');
// configure database etc.
var server = deployd({
port: process.env.PORT || 5000,
env: 'production',
db: {
host: '0.0.0.0',
port: 5000,
name: 'database_name',
credentials: {
username: 'username',
password: 'password'
}
}
});
// heroku requires these settings for sockets to work
server.sockets.server.set('transports', ["xhr-polling"]);
// start the server
server.listen();
// debug
server.on('listening', function() {
console.log("Server is listening on port: " + process.env.PORT);
});
// Deployd requires this
server.on('error', function(err) {
console.error(err);
process.nextTick(function() { // Give the server a chance to return an error
process.exit();
});
});
ERROR:
db:error Error: Cannot open store: MongoError: server 0.0.0.0:5000 timed out
at /home/nitrous/Find-Volunteerships/node_modules/deployd/lib/db.js:144:17
at /home/nitrous/Find-Volunteerships/node_modules/mongodb/lib/mongo_client.js:330:20
at /home/nitrous/Find-Volunteerships/node_modules/mongodb/lib/db.js:231:14
at null.<anonymous> (/home/nitrous/Find-Volunteerships/node_modules/mongodb/lib/server.js:240:9)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at /home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:493:23
at commandCallback (/home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:1149:20)
at Callbacks.flushConnection (/home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:103:9)
at null.<anonymous> (/home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:408:24)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous> (/home/nitrous/Find- Volunteerships/node_modules/mongodb-core/lib/connection/pool.js:144:10)
at g (events.js:260:16)
at emitTwo (events.js:87:13) +0ms
session:error Error removing old sessions: Database connection error +14ms
Unhandled rejection Database connection error
{ [Error: listen EADDRINUSE :::5000]
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 5000 }
You are using same port for two servers.
You can kill one of them with that command
netstat -ano|findstr "PID :5000"
5000 is your port.

Categories

Resources