Can't connect to mongoose/mongodb - mongodb

When I'm trying to add an item to my database I get the following error on the terminal:
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\connection.js:825:32)
at C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:417:10
at C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:1270:10)
at Mongoose.connect (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:416:20)
at Object.<anonymous> (C:\Users\88cro\Desktop\blog\server.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 162133351,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\88cro\Desktop\blog\node_modules\mongodb\lib\cmap\connect.js:387:20)
at Socket.<anonymous> (C:\Users\88cro\Desktop\blog\node_modules\mongodb\lib\cmap\connect.js:310:22)
at Object.onceWrapper (node:events:628:26)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1284:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
Node.js v19.0.1
[nodemon] app crashed - waiting for file changes before starting...
I have MongoDB Atlas and mongoshell installed and running but that doesn't seem to fix the problem.
This is how I setup express and mongoose, I tried to change the url in mongoose.connect but it doesn't seem to work
const express = require('express')
const mongoose = require('mongoose')
const articleRouter = require('./routes/articles')
const app = express()
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => {
const articles = [{
title: 'Test title',
createdAt: new Date(),
description: 'Test description'
}]
res.render('articles/index', { articles: articles })
})
app.use('/articles', articleRouter)
app.listen(5000)
Any ideas about how to fix this? Thanks!

Related

how to fix the error no. -4078, in mongoose connection to the server what's cause this?

What is wrong with this setup
'''
nodejs
'''
require('dotenv').config()
// console.log(process.env)
const express = require('express')
const app = express()
const expressLayouts = require("express-ejs-layouts")
const indexRouter = require('./routes/index')
const mongoose = require('mongoose');
app.set("view engine", "ejs")
app.set("views", __dirname + "/views")
app.set('layout', "layouts/layout")
app.use(expressLayouts)
app.use(express.static('public'))
app.use('/', indexRouter)
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://localhost:27017/printshop',{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
const db = mongoose.connection
db.on('error', error=> console.log(error))
db.once('open', ()=> console.log('connected to mongogoose'))
app.listen(process.env.PORT)
im trying to connect to mongodb in my local network but suddenly this
error message
just out
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (E:\nodejs\node-server\node_modules\mongoose\lib\connection.js:825:32)
at E:\nodejs\node-server\node_modules\mongoose\lib\index.js:417:10
at E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:1270:10)
at Mongoose.connect (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:416:20)
at Object.<anonymous> (E:\nodejs\node-server\server.js:20:10)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1166:10) {
reason: TopologyDescription {
queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
what the mean?
im looking for the log of "connected to mongogoose" but it doesnt show in console then the error comes
ECONNREFUSED ::1:27017
what is this mean?
if anyone had a problem like this you can fix it by changing the
mongoodb://localhost/
to
mongoodb://127.0.0.1/

Get migrations to run on Waterlinejs standalone

Node version: (18.0.0)
DB adapter & version (sails-postgresql#4.0.0):
I kindly require assistance to get migrations to run on waterline standalone version 0.15.0
My config is as follows:
module.exports = {
adapters: {
pg: require('sails-postgresql'),
mysql: require('sails-mysql'),
},
datastores: {
default: {
adapter: 'pg',
host: 'localhost',
port: 5432,
user: 'rcp',
password: 'rcp',
database: 'db_service',
isVersion12OrNewer: true,
},
mysql: {
adapter: 'mysql',
host: 'localhost',
port: 3306,
user: 'db',
password: 'db',
database: 'db_service',
},
},
};
My models:
module.exports = {
identity: 'pet',
datastore: 'default',
primaryKey: 'id',
migrate: 'alter',
attributes: {
id: {
type: 'number',
autoMigrations: { autoIncrement: true },
},
breed: { type: 'string' },
type: { type: 'string' },
name: { type: 'string' },
// Add a reference to User
owner: {
model: 'user',
},
},
};
module.exports = {
identity: 'user',
datastore: 'default',
primaryKey: 'id',
migrate: 'alter',
attributes: {
id: {
type: 'number',
autoMigrations: { autoIncrement: true },
},
firstName: { type: 'string' },
lastName: { type: 'string' },
// Add a reference to Pets
pets: {
collection: 'pet',
via: 'owner',
},
},
};
The bootstrap file:
const Waterline = require('waterline');
const config = require('./config');
const userModel = require('./models/user');
const petModel = require('./models/pet');
const userCollection = Waterline.Collection.extend(userModel);
const petCollection = Waterline.Collection.extend(petModel);
const waterline = new Waterline();
waterline.registerModel(userCollection);
waterline.registerModel(petCollection);
waterline.initialize(config, function (err, ontology) {
if (err) {
console.error(err.message);
return;
}
// Tease out fully initialized models.
let User = ontology.collections.user;
let Pet = ontology.collections.pet;
// Since we're using `await`, we'll scope our selves an async IIFE:
(async () => {
// First we create a user
const user = await User.create({
firstName: 'Neil',
lastName: 'Armstrong',
});
// Then we create the pet
const pet = await Pet.create({
breed: 'beagle',
type: 'dog',
name: 'Astro',
owner: user.id,
});
// Then we grab all users and their pets
const users = await User.find().populate('pets');
console.log(users);
})()
.then(() => {
// All done.
})
.catch((err) => {
console.error(err.message);
}); //_∏_
});
My package.json:
{
"name": "db-service",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "nodemon index.js"
},
"dependencies": {
"sails-mysql": "^2.0.0",
"sails-postgresql": "^4.0.0",
"waterline": "^0.15.0"
},
"devDependencies": {
"nodemon": "^2.0.18"
}
}
The issue I am facing is that when I run the bootstrap file, I get the error below:
Unexpected error from database adapter: relation "public.user" does not exist
Any assistance on this is highly appreciated.
Error Stack:
OperationalError [AdapterError]: Unexpected error from database adapter: relation "public.user" does not exist
at callback (/Users/.../Downloads/musings/db-service/index.js:20:27)
... 20 lines matching cause stack trace ...
at Connection.emit (node:events:539:35) {
cause: Error [AdapterError]: Unexpected error from database adapter: relation "public.user" does not exist
at callback (/Users/.../Downloads/musings/db-service/index.js:20:27)
at /Users/.../Downloads/musings/db-service/node_modules/waterline/lib/waterline.js:731:14
at /Users/.../Downloads/musings/db-service/node_modules/async/dist/async.js:952:25
at iteratorCallback (/Users/.../Downloads/musings/db-service/node_modules/async/dist/async.js:997:17)
at /Users/.../Downloads/musings/db-service/node_modules/async/dist/async.js:847:20
at /Users/.../Downloads/musings/db-service/node_modules/waterline/lib/waterline/utils/system/validate-datastore-connectivity.js:42:14
at /Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:954:24
at handlerCbs.success (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:814:26)
at Object.releaseConnection (/Users/.../Downloads/musings/db-service/node_modules/machinepack-postgresql/machines/release-connection.js:79:18)
at wrapper (/Users/.../Downloads/musings/db-service/node_modules/#sailshq/lodash/lib/index.js:3282:19)
at parley.retry (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:1076:19)
at parley (/Users/.../Downloads/musings/db-service/node_modules/parley/lib/parley.js:140:5)
at Object.runFn [as releaseConnection] (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:461:23)
at /Users/.../Downloads/musings/db-service/node_modules/waterline/lib/waterline/utils/system/validate-datastore-connectivity.js:35:27
at /Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:954:24
at handlerCbs.success (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:814:26)
at PendingItem.cb [as callback] (/Users/.../Downloads/musings/db-service/node_modules/machinepack-postgresql/machines/get-connection.js:87:20)
at BoundPool._acquireClient (/Users/.../Downloads/musings/db-service/node_modules/pg-pool/index.js:298:21)
at /Users/.../Downloads/musings/db-service/node_modules/pg-pool/index.js:270:21
at Connection.<anonymous> (/Users/.../Downloads/musings/db-service/node_modules/pg/lib/client.js:253:7)
at Object.onceWrapper (node:events:642:26)
at Connection.emit (node:events:539:35) {
adapterMethodName: 'create',
modelIdentity: 'user',
raw: error: relation "public.user" does not exist
at Parser.parseErrorMessage (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at Readable.push (node:internal/streams/readable:234:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 110,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '13',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '1363',
routine: 'parserOpenTable'
}
},
isOperational: true,
adapterMethodName: 'create',
modelIdentity: 'user',
raw: error: relation "public.user" does not exist
at Parser.parseErrorMessage (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at Readable.push (node:internal/streams/readable:234:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 110,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '13',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '1363',
routine: 'parserOpenTable'
}
}

Puppeteer on Raspberry Pi fails to start chromium-browser: Error: read ECONNRESET

I am trying to run puppeteer on a Raspberry Pi 4 with Ubuntu installed.
const puppeteer = require('puppeteer');
async function configureBrowser() {
// error here
var browser1 = await puppeteer.launch({ headless: true, executablePath: '/usr/bin/chromium-browser', args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
await page.goto('www.google.com');
return page;
}
async function monitor() {
let page = await configureBrowser();
}
monitor().catch(error => { console.error("Something bad happened...", error); });
It produces the error below from the chromium-browser. Does anyone know what this means? I have tried installing extra dependencies and various options for the browser launch, but nothing yet works. It is a Raspberry Pi 4 that I ssh into.
(node:2870) ExperimentalWarning: The fs.promises API is experimental
Something bad happened... ErrorEvent {
target:
WebSocket {
_events:
[Object: null prototype] { open: [Function], error: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
_binaryType: 'nodebuffer',
_closeCode: 1006,
_closeFrameReceived: false,
_closeFrameSent: false,
_closeMessage: '',
_closeTimer: null,
_extensions: {},
_protocol: '',
_readyState: 3,
_receiver: null,
_sender: null,
_socket: null,
_bufferedAmount: 0,
_isServer: false,
_redirects: 0,
_url:
'ws://127.0.0.1:35593/devtools/browser/b4694718-7829-4f29-945a-1a16d20455a8',
_req: null },
type: 'error',
message: 'read ECONNRESET',
error:
{ Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' } }

Trying to connect cluster to application

Im getting this error when I'm connecting my MongoDB Atlas cluster to my application and I am not sure what how to fix this issue as I have whitelisted all IP addresses as well. The code and the error are shown below:
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+srv://surpol:mypassword123#cluster0.kiwls.mongodb.net/mydb123?retryWrites=true&w=majority', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log(err);
});
MongooseServerSelectionError: connection <monitor> to 54.156.90.92:27017 timed out
at NativeConnection.Connection.openUri (/Users/suryapolina/Documents/GitHub/Phaseify/backend/node_modules/mongoose/lib/connection.js:828:32)
at Mongoose.connect (/Users/suryapolina/Documents/GitHub/Phaseify/backend/node_modules/mongoose/lib/index.js:335:15)
at Object.<anonymous> (/Users/suryapolina/Documents/GitHub/Phaseify/backend/server.js:15:10)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
message: 'connection <monitor> to 54.156.90.92:27017 timed out',
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: 'atlas-wpf52v-shard-0',
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'cluster0-shard-00-00.kiwls.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.kiwls.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.kiwls.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: 30,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: 8
}
}

Can't provoke MongoError - bad auth

Just to be clear, I want to get MongoError bad auth Authentication failed from MongoDB Atlas.
This is about wrong DB password and I'm trying to catch that error and act accordingly.
this is my connection method:
mongoose
.connect(CRED, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => {
console.log('connected to database');
});
and here I'm catching unhandledRejection error that supposed to catch wrong auth:
process.on('unhandledRejection', err => {
console.log(err.name, err.message);
server.close(() => {
process.exit(1);
});
});
If I put correct password, everything works fine and I'm connected to database.
But if I put wrong password, after 30 sec of waiting I get:
MongooseTimeoutError Server selection timed out after 30000 ms
...and this shouldn't suppose to work like that.
I should get MongoError (bad auth) immediately, on first attempt when app is connecting to MongoDB
...or am I doing something wrong?
It's known issue for Mongoose <=5.7.1 with useUnifiedTopology: true option.
Update your Mongoose to 5.9.2 to fix the issue.
With new version, Mongoose fails corectly:
MongooseServerSelectionError MongooseError [MongooseServerSelectionError]: Authentication failed.
at new MongooseServerSelectionError (D:\myapp\node_modules\mongoose\lib\error\serverSelection.js:22:11)
at NativeConnection.Connection.openUri (D:\myapp\node_modules\mongoose\lib\connection.js:808:32)
at Mongoose.connect (D:\myapp\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (D:\myapp\app.js:46:10)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
message: 'Authentication failed.',
name: 'MongooseServerSelectionError',
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
},
[Symbol(mongoErrorContextSymbol)]: {}
}
Also, add .catch clause to your code
mongoose
.connect(CRED, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => {
console.log('connected to database');
})
.catch(error => {
//MongooseServerSelectionError MongooseError [MongooseServerSelectionError]: Authentication failed
console.log("Error", error)
});