the automatic reconnection function natively embedded in mongoose does not work on my project.
I actually receive a return in error but it does not start again after the X seconds that I configured.
Beyond whether the credentials are correct or not, I expect mongoose to try to log in every X seconds (and therefore send me a log each time) but it is not
Here is the doc in question: https://mongoosejs.com/docs/connections.html#options
Here is my code:
import mongoose from "mongoose"
const options = {
dbName: "testbdd",
pass: "qwe",
user: "alex",
useNewUrlParser: true,
serverSelectionTimeoutMS: 1000,
heartbeatFrequencyMS: 1000,
useUnifiedTopology: true
}
const uri = `mongodb://localhost/`
mongoose.connection.on('disconnected', function () {
console.log('Mongo db disconnected!');
});
mongoose.connect(uri, options).then(() => {
console.log('First Mongo db connexion success !')
}).catch((error) => {
console.log('First Mongo db connexion fail !')
console.log(error)
})
Here is the return when I run the node server:
backend_1 | Mongo db disconnected!
backend_1 | First Mongo db connexion fail !
backend_1 | MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
backend_1 | at NativeConnection.Connection.openUri (/user/app/node_modules/mongoose/lib/connection.js:800:32)
backend_1 | at /user/app/node_modules/mongoose/lib/index.js:341:10
backend_1 | at /user/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
backend_1 | at new Promise (<anonymous>)
backend_1 | at promiseOrCallback (/user/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
backend_1 | at Mongoose.connect (/user/app/node_modules/mongoose/lib/index.js:340:10)
backend_1 | at Object.connect (/user/app/src/db/mongo/index.js:28:10)
backend_1 | at Module._compile (internal/modules/cjs/loader.js:776:30)
backend_1 | at Module._compile (/user/app/node_modules/pirates/lib/index.js:99:24)
backend_1 | at Module._extensions..js (internal/modules/cjs/loader.js:787:10)
backend_1 | at Object.newLoader [as .js] (/user/app/node_modules/pirates/lib/index.js:104:7)
backend_1 | at Module.load (internal/modules/cjs/loader.js:643:32)
backend_1 | at Function.Module._load (internal/modules/cjs/loader.js:556:12)
backend_1 | at Module.require (internal/modules/cjs/loader.js:683:19)
backend_1 | at require (internal/modules/cjs/helpers.js:16:16)
backend_1 | at Object.require (/user/app/src/bin/www.js:7:1) {
backend_1 | message: 'connect ECONNREFUSED 127.0.0.1:27017',
backend_1 | reason: TopologyDescription {
backend_1 | type: 'Single',
backend_1 | setName: null,
backend_1 | maxSetVersion: null,
backend_1 | maxElectionId: null,
backend_1 | servers: Map { 'localhost:27017' => [ServerDescription] },
backend_1 | stale: false,
backend_1 | compatible: true,
backend_1 | compatibilityError: null,
backend_1 | logicalSessionTimeoutMinutes: null,
backend_1 | heartbeatFrequencyMS: 1000,
backend_1 | localThresholdMS: 15,
backend_1 | commonWireVersion: null
backend_1 | }
backend_1 | }
Those options should work well, no ?
serverSelectionTimeoutMS: 1000,
heartbeatFrequencyMS: 1000,
useUnifiedTopology: true
I am really lost. I doubt it's the mongoose code that doesn't work, it's necessarily my implementation.
Can you help me ?
This is the intended behavior of the mongodb driver
https://jira.mongodb.org/browse/NODE-834?focusedCommentId=1412582&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-1412582
The driver will fail on first connect if it cannot connect to the host. This is by design to ensure quick failure on unreachable hosts. Reconnect behavior only kicks in once the driver has performed the initial connect.
Related
I am trying to host a discord bot on my ubuntu server.
Everything was working but for some reason it just stopped working and it shows the same error all the time, no matter what i change.
const Discord = require('discord.js');
const client = new Discord.Client({intents: ["MessageContent"]});
client.login("My bots token")
console.log(client);
client.on('message', message => {
if (message.content === '!hello') {
message.channel.send('Nazdar!');
}
})
client.once('ready', () => {
console.log('Ready!');
})
The error message:
> 0|index | at Module._compile (node:internal/modules/cjs/loader:1275:14)
> 0|index | at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
> 0|index | at Module.load (node:internal/modules/cjs/loader:1133:32)
> 0|index | at Module._load (node:internal/modules/cjs/loader:972:12)
> 0|index | ReferenceError: Client is not defined
> 0|index | at Object.<anonymous> (/root/pives-bot/index.js:5:1)
> 0|index | at Module._compile (node:internal/modules/cjs/loader:1275:14)
> 0|index | at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
> 0|index | at Module.load (node:internal/modules/cjs/loader:1133:32)
> 0|index | at Module._load (node:internal/modules/cjs/loader:972:12)
> 0|index | at Object.<anonymous> (/root/.nvm/versions/node/v19.6.1/lib/node_modules/pm2/lib/ProcessContainerFork.js:33:23)
> 0|index | at Module._compile (node:internal/modules/cjs/loader:1275:14)
> 0|index | at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
> 0|index | at Module.load (node:internal/modules/cjs/loader:1133:32)
> 0|index | at Module._load (node:internal/modules/cjs/loader:972:12)
>
I tried changing all forms of uppercase or lowercase characters, but still the same issue. Thanks for every help!!
I have a Node/Express backend that I created almost 2 years ago and it has worked without fail until now. I loaded up my dev server for the first time in around a month and my backend is now showing this error:
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\taxi-booker\backend\node_modules\mongoose\lib\connection.js:845:32)
at C:\taxi-booker\backend\node_modules\mongoose\lib\index.js:348:10
at promiseOrCallback (C:\taxi-booker\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:9:12)
at Mongoose._promiseOrCallback (C:\taxi-booker\backend\node_modules\mongoose\lib\index.js:1152:10)
at Mongoose.connect (C:\taxi-booker\backend\node_modules\mongoose\lib\index.js:347:20)
at accountDBHandler.build (C:\taxi-booker\backend\DBHandlers\accountsDB.js:16:20)
at C:\taxi-booker\backend\serverClass.js:640:27
at Layer.handle [as handle_request] (C:\taxi-booker\backend\node_modules\express\lib\router\layer.js:95:5)
at next (C:\taxi-booker\backend\node_modules\express\lib\router\route.js:137:13)
at C:\taxi-booker\backend\serverClass.js:71:6
at C:\taxi-booker\backend\node_modules\jsonwebtoken\verify.js:223:12
at getSecret (C:\taxi-booker\backend\node_modules\jsonwebtoken\verify.js:90:14)
at Object.module.exports [as verify] (C:\taxi-booker\backend\node_modules\jsonwebtoken\verify.js:94:10)
at checkToken (C:\taxi-booker\backend\serverClass.js:66:8)
at Layer.handle [as handle_request] (C:\taxi-booker\backend\node_modules\express\lib\router\layer.js:95:5)
at next (C:\taxi-booker\backend\node_modules\express\lib\router\route.js:137:13)
{ reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null } }
This error was caught here:
async build() {
try {
if (mongoose.connection.readyState !== 1) {
await mongoose.connect(
this.connectionURL,
{
useNewUrlParser: true,
useUnifiedTopology: true
},
err => {
if (err) {
console.error(err);
console.log("connection error");
} else {
console.log(chalk.greenBright("Successful connection to database"));
}
}
);
mongoose.pluralize(null);
}
this.accounts = mongoose.model("Accounts", accountSchema);
} catch (err) {
console.error(err);
}
}
I am using the following versions:
Node 17.3
MongoDB 4.2.6
Mongoose 5.12.3
Windows 10
I can also connect to my DB perfectly fine through Compass.
I use npm consul client.
I have set CONSUL_HTTP_TOKEN as environment variable, and tried to create token using consul.acl.create but I get Permission denied
//code
const express = require("express");
const consul = require("consul")();
console.log('Bootstrap token is ', process.env.CONSUL_HTTP_TOKEN);
consul.acl.create((err, result) => {
if(err) {
console.error('found error', err);
}});
Output is :
Bootstrap token is AccessorID: 9d0d8271-b8aa-6b03-c4f5-dce653853653
consul_1 | SecretID: f4a6ffc0-2a16-517e-d1c5-645eaaeb5f7a
consul_1 | Description: Bootstrap Token (Global Management)
consul_1 | Local: false
consul_1 | Create Time: 2021-03-19 20:19:16.9918012 +0000 UTC
consul_1 | Policies:
consul_1 | 00000000-0000-0000-0000-000000000001 - global-management
2021-03-19T20:19:17.139Z [ERROR] agent.http: Request error: method=PUT url=/v1/acl/create from=127.0.0.1:43776 error="Permission denied"
consul_1 | 2021-03-19T20:19:17.139Z [DEBUG] agent.http: Request finished: method=PUT url=/v1/acl/create from=127.0.0.1:43776 latency=170.7µs
consul_1 | found error Error: Permission denied
consul_1 | at create (/app/node_modules/papi/lib/errors.js:14:5)
consul_1 | at Object.response [as Response] (/app/node_modules/papi/lib/errors.js:38:15)
consul_1 | at IncomingMessage.<anonymous> (/app/node_modules/papi/lib/client.js:592:26)
consul_1 | at IncomingMessage.emit (events.js:326:22)
consul_1 | at endReadableNT (_stream_readable.js:1241:12)
consul_1 | at processTicksAndRejections (internal/process/task_queues.js:84:21) {
consul_1 | isPapi: true,
consul_1 | isResponse: true,
consul_1 | statusCode: 403
consul_1 | }
Config.json :
{
"acl": {
"enabled": true,
"default_policy": "deny",
"enable_token_persistence": true
}
}
The Consul client package will not automatically use the Consul token from the CONSUL_HTTP_TOKEN environment variable. You must explicitly define a token to use either when initializing the Consul client, or for each request.
For example:
import consul from 'consul';
// Read Consul token from environment variable
const bootstrapToken = process.env.CONSUL_HTTP_TOKEN;
// Initialize the Consul client
// Set a token to be used by default for every request
const defaultClientOptions = {
defaults: {
token: bootstrapToken
}
}
const consulClient = new consul(defaultClientOptions);
// Query KV store for key 'test'
let kvQueryOptions = { key: 'test' }
consulClient.kv.get(kvQueryOptions, function (err, result) {
if (err) throw err;
if (!result) {
console.log(`Key '${kvQueryOptions.key}' does not exist.`)
return;
}
result.forEach(item => {
console.log(item);
});
});
// Query for key 'test2'
// Override the default token with a different token for this request
kvQueryOptions = {
key: 'test2',
token: 'C601F13E-AF45-4674-B6AB-BA50299DA0A4'
}
consulClient.kv.get(kvQueryOptions, function (err, result) {
if (err) throw err;
if (!result) {
console.log(`Key '${kvQueryOptions.key}' does not exist.`)
return;
}
result.forEach(item => {
console.log(item);
});
});
const express = require('express')
const User = require('../models/User')
const auth = require('../middleware/auth')
const router = express.Router()
router.post('/users', async (req, res) => {
// Create a new user
try {
const user = new User(req.body)
const status = 1
await user.save()
const token = await user.generateAuthToken()
res.status(201).send({status, user, token })
} catch (error) {
res.status(400).send(error)
}
})
router.post('/users/login', async(req, res) => {
//Login a registered user
try {
const { email, password } = req.body
const user = await User.findByCredentials(email, password)
const status = 1
if (!user) {
return res.status(401).send({error: 'Login failed! Check authentication credentials'})
}
const token = await user.generateAuthToken()
res.send({ status,user,token })
} catch (error) {
res.status(400).send(error)
}
})
router.get('/users/me', auth, async(req, res) => {
// View logged in user profile
res.send(req.user)
})
router.post('/users/me/logout', auth, async (req, res) => {
// Log user out of the application
try {
req.user.tokens = req.user.tokens.filter((token) => {
return token.token != req.token
})
await req.user.save()
res.send()
} catch (error) {
res.status(500).send(error)
}
})
router.post('/users/me/logoutall', auth, async(req, res) => {
// Log user out of all devices
try {
req.user.tokens.splice(0, req.user.tokens.length)
await req.user.save()
res.send()
} catch (error) {
res.status(500).send(error)
}
})
router.patch('/users/places/:id', auth, async (req, res) => {
const updates = Object.keys(req.body)
const allowedUpdates = ['places']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send({ error: 'Invalid updates!' })
}
try {
const task = await Task.findOne({ _id: req.params.id})
if (!task) {
return res.status(404).send()
}
else{
updates.forEach((update) => {
task[update] = update === 'places'
? task[update].map(places=>places.place === req.body[update].place ? req.body[update] : places)
: req.body[update]
})
updates.forEach((update) => {
task[update] = update === 'places'
? task[update].map(places=>places.latitude === req.body[update].latitude ? req.body[update] : places)
: req.body[update]
})
updates.forEach((update) => {
task[update] = update === 'places'
? task[update].map(places=>places.longitude === req.body[update].longitude ? req.body[update] : places)
: req.body[update]
})
}
await task.save()
res.send(task)
} catch (e) {
res.status(400).send(e)
})
module.exports = router
It is showing an error at line no 102
Unexpected end of input as error and I am not able to understand the error as I am new to the code in nodejs.
below given is the log of the yarn run v1.22.4
4:23:43 PM web.1 | $ env-cmd -f ./.env node src/app.js
4:23:44 PM web.1 | H:\Minor\Backend\src\ro
4:23:44 PM web.1 | uters\user.js:106
4:23:44 PM web.1 | module.exports = router
4:23:44 PM web.1 | SyntaxError: Unexpected end of input
4:23:44 PM web.1 | at wrapSafe (internal/modules/cjs/loader.js:1072:16)
4:23:44 PM web.1 | at Module._compile (internal/modules/cjs/loader.js:1122:27)
4:23:44 PM web.1 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
4:23:44 PM web.1 | at Module.load (internal/modules/cjs/loader.js:1002:32)
4:23:44 PM web.1 | at Function.Module._load (internal/modules/cjs/loader.js:901:14)
4:23:44 PM web.1 | at Module.require (internal/modules/cjs/loader
4:23:44 PM web.1 | .js:1044:19)
4:23:44 PM web.1 | at require (internal/modules/cjs/helpers.js:77:18)
4:23:44 PM web.1 | at Object.<anonymous> (H:\Minor\Backend\src\app.js:3:20)
4:23:44 PM web.1 | at Module._compile (internal/modules/cjs/loader.js:1158:30)
4:23:44 PM web.1 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
4:23:44 PM web.1 | error Command failed with exit code 1.
4:23:44 PM web.1 | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[DONE] Killing all processes with signal SIGINT
4:23:44 PM web.1 Exited with exit code nullterminal showing the error
the above given is the log of the code running in a terminal
And the error is Unexpected token')'
Please help me in resolving this error
as I am new to node js so I don't know much about it and on google also I am not able to find any solution................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... Please review my code once and help me in resolving it.
It forgot
})
before module.exports = router
Put your code inside it, https://beautifier.io/ and look...
Update:
Yep, look at the last try catch :
} catch (e) {
res.status(400).send(e)
}) // <--- remove the )
})
I need help...
So, I have this code
var express = require('express');
var app = express();
//Sites
// Landingpage CourseWorkers ----------------------------------------
app_courseworkers = require('./sites/app')
app_https_courseworkers = (req, response) => response.redirect("https://courseworkers.com")
But when I run it on the server I get the message:
0|index | TypeError: response.redirect is not a function
0|index | at Object.app_https_courseworkers [as handler] (/var/www/html/courseworkers/index.js:9:55)
0|index | at Server.overallHandler (/var/www/html/courseworkers/node_modules/vhttps/lib/init.js:103:25)
0|index | at emitTwo (events.js:126:13)
0|index | at Server.emit (events.js:214:7)
0|index | at parserOnIncoming (_http_server.js:619:12)
0|index | at HTTPParser.parserOnHeadersComplete (_http_common.js:115:23)
Can anyone point out what I'm doing wrong?
Note: Running in localhost it goes normally
If you are trying to redirect to an external URL when someone goes to a specific URL on your site, try this:
app.get("/course", (req, res) => {
res.redirect("https://courseworkers.com");
});
My guess is, you are trying to call app_https_courseworkers(req, response), but you aren't actually passing in a valid response object.