I've checked around Stack and the Mongoose docs for this, but I can't seem to get it right. As implied in the title everything was fine until i upgraded the packages for mongoose and connect-mongo.
Here's my database.js:
var mongoose = require('mongoose');
var mongodbUri = require('mongodb-uri');
function encodeMongoURI (urlString) {
if (urlString) {
var parsed = mongodbUri.parse(urlString)
urlString = mongodbUri.format(parsed);
}
return urlString;
}
mongoose.connect(encodeMongoURI(process.env.MONGODB_URI) || 'mongodb://localhost:27017/goGradesDB',//specifies goGradesDB as the db to use locally
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
}).catch(error => handleError(error));
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
module.exports = db;
After looking over the docs in mongoose and searching this site I've tried the following:
installed the mongodb-uri package to parse the uri (although I'm not sure if that's needed for the local db. I can't get onto my heroku db either, but that's something I'm working with support on.
added the "useNewURLParser", etc. tag.
added the port number into the local db address
added the catch onto the end of mongoose.connect
Despite this I keep getting the following error output in my terminal and the db times out whenever I try to login to the app. Here's the output:
"The server is running on port 3000!
(node:71951) UnhandledPromiseRejectionWarning: MongoParseError: URI malformed, cannot be parsed"
and later,
"(node:71951) 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(). (rejection id: 2)
(node:71951) [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."
Any insight would be much appreciated. Thank you!
Related
This question already has answers here:
MongooseError - Operation `users.findOne()` buffering timed out after 10000ms
(17 answers)
Closed 1 year ago.
My js file wont respond and it will trow me this error in the console wich i don't understand:
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Backend server is running
Connected to MONGODB
(node:5282) UnhandledPromiseRejectionWarning: MongooseError: Operation
`users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (/home/francesco/Desktop/Projects/Social Network/NODE-REST-
API/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:149:23)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5282) 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:5282) [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.
This is the code of the module (btw dont mind but th "ok" its for testing.
const router = require("express").Router();
const User = require("../models/User")
//REGISTER
router.get("/register", async (req,res)=>{
const user = await new User({
username:"john",
email:"john#gmail.com",
password:"123456"
})
await user.save();
res.send("ok");
});
module.exports = router
the syntax is right, needed to format it for containing on the "code" on the question.
Thanks in advance, Francesco
You are trying to call the model without even establishing a connection with the database. You need to use async/await with connect() or createConnection().
I am able to start the server but cannot able to run the web app as localhost getting the below error
Server started on port 3000
(node:13052) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT cluster0.3zwxl.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19)
(node:13052) 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:13052) [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.
Here is my url
mongoose.connect("mongodb+srv://xxxxxxxx:vikas#cluster0.3zwxl.mongodb.net/xxxxxx",{useNewUrlParser:true,useUnifiedTopology: true});
Moreover the webapp is not loading and getting "This site can’t be reached"
I was also facing the same issue today itself.. and i found some of the solutions mentioned below:
Changing the DNS
Adding current IP to whitelist section of your mongodb
Connecting with the same network that you've configured with
Solution No. 3 worked for me... as soon as i connected to my network which i had configured with i got console Connected to database... and as soon as i change my network again i got the error
you can see the image when i connected back to previous network it was working but when i changed my network i got the error
I had fixed my issue
mongoose.connect("mongodb+srv://xxxxxxxx:xxxxxxxx#cluster0.3zwxl.mongodb.net/xxxxxx?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology: true});
mongoose.connection.on("connected",()=>{
console.log("Mongoose connected");
})
better approach for multiple connections for future use
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
console.log("MONGODB: Default Connection Established");
} catch (error) {
console.log(error);
process.exit(1);
}
}
connectDB();
My Node.js app is able to work with local Postgres database via npm pg module.
I can connect to the Heroku hosted Postgres database (free Hobby Dev plan) via command line with heroku pg:psql command as well.
But when my Node.js app is trying to query to Heroku hosted Postgres database I am receiving an self signed certificate error.
Here is the output with self signed certificate error:
(node:2100) UnhandledPromiseRejectionWarning: Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1051:34)
at TLSSocket.emit (events.js:189:13)
at TLSSocket._finishInit (_tls_wrap.js:633:8)
(node:2100) 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(). (rejection id: 1)
(node:2100) [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.
D:\MY\DEV\PROJECTS\AdsSubscribeBot\test.js:57
if (err) throw err;
^
Error: Connection terminated unexpectedly
at Connection.con.once (D:\MY\DEV\PROJECTS\AdsSubscribeBot\node_modules\pg\lib\client.js:264:9)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Socket.<anonymous> (D:\MY\DEV\PROJECTS\AdsSubscribeBot\node_modules\pg\lib\connection.js:76:10)
at Socket.emit (events.js:194:15)
at TCP._handle.close (net.js:597:12)
Simpliest way to reproduce this error is to try use the sample code to connecting in Node.js from Heroku devcenter:
https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js
Here is the sample of the code that causes self signed certificate error:
const connectionString = 'postgres://USERNAME:PASSWORD#HOST:PORT/DB_NAME';
const { Client } = require('pg');
const client = new Client({
connectionString: connectionString,
ssl: true
});
client.connect();
client.query('SELECT * FROM users;', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
Maybe someone has faced the same issue and know the way how to solve it.
Thanks in advance for any help.
Check you pg config. It sounds like you are using pg 8 which deprecates
implicit disabling of certificate verification (as you have in your config where ssl is set to true but no ssl configuration is provided). Specify rejectUnauthorized: true to require a valid CA or rejectUnauthorized: false to explicitly opt out of MITM protection.
You can do so where you set up your pg config as follows
const client = new Client({
connectionString: connectionString,
ssl: { rejectUnauthorized: false }
})
If anyone is still seeing issues with this after appending the SSL object to the Client object and they are using a connection string. Make sure that you don't have an ssl parameter in the connection string. If you are working with Digital Ocean this parameter is included in the generated connection string.
This is how Digital Ocean formats their connection strings by default
postgres://USERNAME:PASSWORD#HOST:PORT/DB_NAME:25060/defaultdb?&sslmode=require
To get this to work, I had to add:
ssl: { rejectUnauthorized: false }
but also add this to the environment:
NODE_TLS_REJECT_UNAUTHORIZED=0
Below is a variation of the accepted answer using Knex.js. Tested on Heroku.
const parse = require('pg-connection-string').parse;
const pgconfig = parse('your-pg-connection-string');
pgconfig.ssl = { rejectUnauthorized: false };
const knex = Knex({
client: 'pg',
connection: pgconfig,
});
Thanks to #samkhan27. I just added ssl: { rejectUnauthorized: false }
My full code:
const db = new Sequelize(
process.env.DATABASE_URL ||
`postgres://postgres:w2w2#localhost:5432/${databaseName}`,
{
logging: false,
ssl: { rejectUnauthorized: false } //solved the problem with self signed sertificate
}
)
I'm new to both Node.js and Tensorflow so I apologize if this is kind of stupid. I'm also new to Stack Overflow so I apologize if this isn't the best-formatted question. I'm trying to implement Tensorflow into a Discord bot(to make a chatbot). I have some experience in Java so I was able to fix some node.js errors, but I can't figure out what this error means as it appears to be a Tensorflow error, not a node.js error and I'm completely new to Tensorflow. One more thing: I am using the provided example code found at https://www.tensorflow.org/js/guide/nodejs except for import * as tf from '#tensorflow/tfjs-node' which I replaced with const tf = require('#tensorflow/tfjs-node'); since import gives an error.
The error I am getting:
2020-03-25 21:02:38.317965: W tensorflow/core/framework/op_kernel.cc:1651] OP_REQUIRES failed at summary_kernels.cc:57 : Not found: Failed to create a directory: \/tmp; No such file or directory
(node:3504) UnhandledPromiseRejectionWarning: Error: Invalid TF_Status: 5
Message: Failed to create a directory: \/tmp; No such file or directory
at NodeJSKernelBackend.executeMultipleOutputs (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\nodejs_kernel_backend.js:206:43)
at NodeJSKernelBackend.createSummaryFileWriter (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\nodejs_kernel_backend.js:1580:14)
at Object.summaryFileWriter (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\tensorboard.js:98:17)
at TensorBoardCallback.ensureValWriterCreated (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\callbacks.js:310:40)
at TensorBoardCallback.logMetrics (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\callbacks.js:296:22)
at TensorBoardCallback.<anonymous> (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\callbacks.js:262:26)
at step (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\callbacks.js:61:23)
at Object.next (C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\callbacks.js:42:53)
at C:\Users\BCG04\node_modules\#tensorflow\tfjs-node\dist\callbacks.js:36:71
at new Promise (<anonymous>)
(node:3504) 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: 3)
(node:3504) [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.
This is the code with the error:
client.once('ready', () => {
//Start TENSORFLOW tests
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [200] }));
model.compile({
loss: 'meanSquaredError',
optimizer: 'sgd',
metrics: ['MAE']
});
// Generate some random fake data for demo purpose.
const xs = tf.randomUniform([10000, 200]);
const ys = tf.randomUniform([10000, 1]);
const valXs = tf.randomUniform([1000, 200]);
const valYs = tf.randomUniform([1000, 1]);
// Start model training process.
async function train() {
await model.fit(xs, ys, {
epochs: 100,
validationData: [valXs, valYs],
// Add the tensorBoard callback here.
callbacks: tf.node.tensorBoard('/tmp/fit_logs_1')
});
}
train();
//End TENSORFLOW tests
console.log('Ready!');
console.log("Servers:")
client.guilds.cache.map((guild) => {
console.log(" - " + guild.name)
// List all channels
client.guilds.cache.map((channel) => {
console.log(` -- ${channel.name} (${channel.type}) - ${channel.id}`)
});
});
});
As you are running on windows machine, this directory is invalid.
Please replace this line callbacks: tf.node.tensorBoard('/tmp/fit_logs_1') with this
callbacks: tf.node.tensorBoard('C:\\Users\\BCG04')
It seems you dont have access to create tmp folder on root as indicated on the code tf.node.tensorBoard('/tmp/fit_logs_1'). Try to change the path.
For me i've change it into tf.node.tensorBoard('.tmp/fit_logs_1') so it will create .tmp directory on current working path.
I have a problem with the connection to my database located in Azure, I was attempting to do a connection with a rest-API that I create, to a database that I have in Azure, this database I manage directly from SQL Server, and I can't make a connection with this.
I attempt to connect with another test database in SQL Server.
The rest-API ia create is in NodeJS
var sql = require('mssql');
var dbconfig = {
server:"Fernando\EQUIPO",
user: "<user>",
password: "<password>",
database: "<dbname>",
port: 1433,
option: {
encrypt: false
}
};
function getList() {
var record;
var conn = new sql.ConnectionPool(dbconfig);
conn.connect(function(err){
if(err) throw err;
var req = new sql.Request(conn);
req.query("select * from cliente", function(err, recordset) {
if(err) throw err;
else {
console.log(recordset);
record = recordset;
}
conn.close();
});
});
return record;
}
const { Router } = require('express');
const router = Router();
const _ = require('underscore');
const movies = require('../sample.json');
router.get('/', (req, res) => {
res.send(getList());
});
When I make a "get" to my local host http://localhost:3000/api/movies appears the following message in the console:
GET /api/movies 200 126.188 ms - -
(node:11868) UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
at Connection.tedious.once.err (C:\Users\luisn\Desktop\rest-API\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.socketError (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1258:12)
at _connector.Connector.execute (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1084:21)
at GetAddrInfoReqWrap._dns.default.lookup [as callback] (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connector.js:152:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:68:17)
(node:11868) 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(). (rejection id: 1)
(node:11868) [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.
Connect to Azure SQL database:
Here's the example code connect to Azure SQL database with REST-API:
Note: the encrypt must be true.
You can get the server name from on Portal:
And you need to add the client IP address to the Azure SQL Server firewall settings:
Then you could connect to the Azure SQL database now. You can reference:Creating a Node.js REST API in Azure
Connect to SQL Server:
Your code is almost correct and need some change:
var sql = require('mssql');
var dbconfig = {
server:"localhost",
user: "<user>",
password: "<password>",
database: "<dbname>",
port: 1433,
option: {
encrypt: false
}
};
Like Abhishek Ranjan said, you should enter your server ip.
Hope this helps.
Welcome to StackOverflow.
ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
Your error states that it is unable to connect as it could not find a server at the given address.Make sure there is a server runninng and verify connection using some third party app.
Are you sure FernandoEQUIPO gets resolved to a proper hostname ?