I'm trying to do user authentification with passport and mongodb but I keep getting an error. I tried restarting the server and looking for places to put an await function but I believe I covered all my tracks. I'm still getting the error and I have no idea why. It might be in the database itself but I am not sure because I'm new to mongodb
the error:
app: authRouter MongoServerError: E11000 duplicate key error collection: mernpractice.users index: email_1 dup key: { email: null }
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\operations\insert.js:51:33
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
app: authRouter at handleOperationResult (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\sdam\server.js:363:9)
app: authRouter at MessageStream.messageHandler (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection.js:479:9)
app: authRouter at MessageStream.emit (events.js:400:28)
app: authRouter at processIncomingData (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
app: authRouter at MessageStream._write (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
app: authRouter at writeOrBuffer (internal/streams/writable.js:358:12)
app: authRouter at MessageStream.Writable.write (internal/streams/writable.js:303:10)
app: authRouter at TLSSocket.ondata (internal/streams/readable.js:726:22) +0ms
(node:484) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'close' of undefined
at addUser (C:\Users\Yanki XXIV\Desktop\pluralsight\src\routers\authRouter.js:29:16)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:484) 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:484) [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.
app: authRouter MongoServerError: E11000 duplicate key error collection: mernpractice.users index: email_1 dup key: { email: null }
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\operations\insert.js:51:33
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
app: authRouter at handleOperationResult (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\sdam\server.js:363:9)
app: authRouter at MessageStream.messageHandler (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection.js:479:9)
app: authRouter at MessageStream.emit (events.js:400:28)
app: authRouter at processIncomingData (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
app: authRouter at MessageStream._write (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
app: authRouter at writeOrBuffer (internal/streams/writable.js:358:12)
app: authRouter at MessageStream.Writable.write (internal/streams/writable.js:303:10)
app: authRouter at TLSSocket.ondata (internal/streams/readable.js:726:22) +9s
(node:484) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'close' of undefined
at addUser (C:\Users\Yanki XXIV\Desktop\pluralsight\src\routers\authRouter.js:29:16)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:484) 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: 2)
auth.js
const express = require('express');
const debug = require('debug')('app: authRouter');
const { MongoClient } = require('mongodb');
const authRouter = express.Router();
authRouter.route('/signUp').post((req, res) => {
const {username, password} = req.body;
const url =
'mongodb+srv://Yoshi:Yumcmaster1#cluster0.atic5.mongodb.net?retryWrites=true&w=majority'
const dbName = 'mernpractice';
(async function addUser(){
let client
try {
let client = await MongoClient.connect(url);
const db = client.db(dbName);
const user = {username, password};
const results = await db.collection('users').insertOne(user);
debug(results);
req.login(results.ops[0], ()=> {
res.redirect('/auth/profile');
});
} catch (error) {
debug(error)
}
client.close();
}());
});
authRouter.route('/profile').get((req, res) => {
res.json(req.user);
})
module.exports = authRouter;
app.js
const express = require('express');
const chalk = require('chalk');
const debug = require('debug')('app');
const morgan = require('morgan');
const path = require('path');
const passport = require('passport');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const PORT = process.env.PORT || 3000;
const app = express();
const sessionsRouter = require('./src/routers/sessionsRouter');
const adminRouter = require('./src/routers/adminRouter');
const authRouter = require('./src/routers/authRouter');
app.use(morgan('tiny'));
app.use(express.static(path.join(__dirname, '/public/')));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieparser());
app.use(session({secret: 'globomantics'}));
require('./src/config/passport.js')(app)
app.set('views', './src/views')
app.set('view engine', 'ejs')
app.use('/sessions', sessionsRouter);
app.use('/admin', adminRouter);
app.use('/auth', authRouter);
app.get('/', (req, res) => {
res.render('index', { title: 'Globomantics', data: ['a','b','c'] });
});
app.listen(PORT, () => {
debug(`listening on port ${chalk.green(PORT)}`);
});
the error "E11000 duplicate key error index: ..." is due to bad data in DB, you need to cleanup your data in collection mernpractice.users as there are multiple records with email missing/null and you have unique index on the email.
you can get all missing emails using query:
db.users.find({
email: {
$exists: false
}
})
or
db.collection.find({
email: null
})
you need to clean all documents with email null or set unique email for all such documents returned by query.
Also when you insert new record you need to ensure email is available otherwise it will insert first record with null but all subsequent inserts will try to insert email as null and throw same error.
pls refer to https://www.mongodb.com/community/forums/t/e11000-duplicate-key-error-collection/14141 and https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field
For me, it was because I set a field say email in a schema to unique. I created a document and set the value of the email to 'exampleemail#example.com'. The problem occurred when I tried to create/update a new document whose value of an email is the same as the above.
Related
I built a NodeJS Express & MongoDB web application that is working well locally.
I tried to deploy it.
Eventhough, the application is partially working in production mode, some of its pages are not displaying.
For example, I'm not able to access the blog page and the following message error displays instead of the content of the page:
Incomplete response received from application
Therefore, I logged the blog page and got the error message below:
App 814821 output: node:internal/process/promises:279 App 814821
output: triggerUncaughtException(err, true /* fromPromise /); App
814821 output: ^ App 814821 output: [UnhandledPromiseRejection: 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(). The promise rejected with the reason "#".] {
App 814821 output: code: 'ERR_UNHANDLED_REJECTION' App 814821 output:
} [ W 2022-11-19 10:30:01.7998 813657/Tg
age/Cor/Con/InternalUtils.cpp:96 ]: [Client 5-1] Sending 502 response:
application did not send a complete response [ N 2022-11-19
10:30:01.8095 813657/Ti age/Cor/CoreMain.cpp:1147 ]: Checking whether
to disconnect long-running connections for process 814821, application
/home/raso1970/node-com4muz (development) App 815207 output:
node:internal/process/promises:279 App 815207 output:
triggerUncaughtException(err, true / fromPromise */); App 815207
output: ^ App 815207 output: [UnhandledPromiseRejection: 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(). The promise rejected with the reason "#".] { App
815207 output: code: 'ERR_UNHANDLED_REJECTION' App 815207 output: } [
W 2022-11-19 10:30:03.7100 813657/Ti age/Cor/Con/InternalUtils.cpp:96
]: [Client 6-1] Sending 502 response: application did not send a
complete response [ W 2022-11-19 10:30:05.0596 813657/T3
age/Cor/App/Poo/AnalyticsCollection.cpp:102 ]: Process (pid=815207,
group=/home/raso1970/node-com4muz (development)) no longer exists!
Detaching it from the pool. [ N 2022-11-19 10:30:05.0597 813657/T3
age/Cor/CoreMain.cpp:1147 ]: Checking whether to disconnect
long-running connections for process 815207, application
/home/raso1970/node-com4muz (development)
I guess the issue comes from MongoDB?
Maybe I did not set up the connection correctly?
Here is my code related to the MongoDB database connection:
data\database.js:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
let database;
let mongodbUrl = 'mongodb://127.0.0.1:27017';
let MONGODB_URL = 'mongodb+srv://<username>:<password>#cluster0.42o6qd6.mongodb.net/?retryWrites=true&w=majority'
if (process.env.MONGODB_URL) {
mongodbUrl = process.env.MONGODB_URL;
}
async function connect() {
const client = await MongoClient.connect(mongodbUrl);
database = client.db('com4muz-blog');
}
function getDb() {
if (!database) {
throw { message: 'Database connection not established!' };
}
return database;
}
module.exports = {
connectToDatabase: connect,
getDb: getDb
};
Indeed, I did write my username and password instead of <username> and <password> to the MONGODB_URL value.
app.js:
const path = require('path');
const express = require('express');
const session = require('express-session');
const sessionConfig = require('./config/session');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const authRoutes = require('./routes/admin/auth');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const authMiddleware = require('./middlewares/auth-middleware');
const mongoDbSessionStore = sessionConfig.createSessionStore(session);
let port = 3000;
if (process.env.MONGODB_URL) {
port = process.env.MONGODB_URL;
}
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session(sessionConfig.createSessionConfig(mongoDbSessionStore)));
app.use(authMiddleware);
app.use('/', adminRoutes);
app.use('/', authRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
console.error(error);
res.status(500).render('500');
});
if (typeof(PhusionPassenger) !== 'undefined') {
PhusionPassenger.configure({ autoInstall: false });
}
if (typeof(PhusionPassenger) !== 'undefined') {
app.listen('passenger');
} else {
app.listen(3000);
}
I'm using o2switch as a hosting server. They use the Setup Node.js App tool, which deploy the website through Phushion Passenger.
Hi I've written the following route for an api endpoint which isn't working. When I test with Postman and my code, it's simply a 404 not found error.
router.patch("/favorite", async (req, res) => {
user = await User.findById(req.body.id)
if (user == null) {
return res.status(404).json({ message: 'Cannot find user' })
}
if (req.body.putArr != null) {
res.user.favPokemon = req.body.putArr;
}
try {
const updatedUser = await res.user.save();
console.log(res.user.favPokemon);
console.log(updateUser);
res.json(updatedUser);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
What am I missing/what error do I have in my code? For reference, here's my mongoDB setup for users:
Edit: Apologies for not specifying the endpoint. To be more clear, the end point and code calling this is:
const favThis = async (e) => { // Patch method to favorite or unfavorite a pokemon
debugger;
e.preventDefault();
try {
console.log(putArr);
const newUser = {userID, putArr};
await axios.patch("http://localhost:5000/users/favorite", newUser);
} catch(err) {
err.response.data.msg && setError(err.response.data.msg)
}
};
, so it's http://localhost:5000/users/favorite. I have other endpoints working fine such as http://localhost:5000/users/login and http://localhost:5000/users/register, and inside server.js I have app.use("/users", require("./routes/users"));
Additionally, server.js is simply
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv").config();
// set up express
const app = express();
app.use(express.json());
app.use(cors());
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`The server has started on port: ${PORT}`));
// set up mongoose
mongoose.connect(
process.env.MONGODB_CONNECTION_STRING,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
},
(err) => {
if (err) throw err;
console.log("MongoDB connection established");
}
);
// set up routes
app.use("/users", require("./routes/users"));
app.use("/todos", require("./routes/todo"));
Edit 2:: I notice now that when I test on Postman, it's an infinite loop and the call is hung. I also get the following warnings in my console:
(node:36447) 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)
and
(node:36447) [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.
Based on the warning you have failing code inside a promise which is not being caught. Perhaps in this line user = await User.findById(req.body.id).
Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai
I am trying to create a web-application with node.js, mongoose and MongoDB,
I am trying to load the web-page localhost:8800/api/auth/register which is stuck at loading since past 15 minutes.
VS Code Terminal return the following :
(node:2908) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (E:\Projects\Applications\chitter-chatter\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2908) 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:2908) [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.
(node:2908) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (E:\Projects\Applications\chitter-chatter\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(node:2908) 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: 4)
My Scripts are as following :
Index.js :
const application = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL, {useNewUrlParser: true, useUnifiedTopology: true}, () => {
console.log("connected to MongoDB")
});
// middleware
application.use(express.json());
application.use(helmet());
application.use(morgan("common"));
application.use("/api/users", userRoute);
application.use("/api/auth", authRoute);
application.listen(8800, () => {
console.log("backend server is running!")
})
Auth.js :
const User = require("../models/User");
// REGISTER
router.get("/register", async (req, res) => {
const user = await new User ({
username: "john",
useremail: "john#gmail.com",
userpswrd: "123456"
})
await user.save();
res.send("oK")
});
module.exports = router
I am also using .env for MONGO VIA URL CONNECTION
Sorry for the bad writing apologies in advance also I am new to this so pls correct me! I know i have done a lot of mistakes,
Thanks for u're sincere time dedication and sympathy
First of all, you must make sure that you are connecting to the database without any error.
To do this, start listening on connect's callback function:
try {
// This configuration is better
mongoose.connect(process.env.MONGO_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
}, err => {
if (err) throw Error(err.message);
console.log("connected to MongoDB");
application.listen(8800, () => console.log("backend server is running!"));
});
} catch (error) {
console.log(error);
}
I think you should make this operation in a try-catch statement like this:
// REGISTER
router.get("/register", async (req, res) => {
try {
// Create user in database
const user = await User.create({
username: "john",
useremail: "john#gmail.com",
userpswrd: "123456"
});
res.status(200).json({ success: true });
} catch (error) {
res.status(500).json({ error });
console.log(error);
}
});
module.exports = router;
Then you can see error's details, and server keeps running.
If you can't solve the problem just add a comment here I'll be back ASAP
check your router or wifi if you are using to run mongoose
try with your mobile internet
I realize this may seem like a duplicate of other questions, but I have looked at every suggested SO question I could find before posting this, and I am looking for help on this specific scenario, as none of the other answers have worked for me.
I have a Node/Express app that is initializing a single MongoDB connection to be used by a REST API. The first step is to connect to the MongoDB instance. If the initial connection fails, it will throw an error as expected. I am using async/await with a try/catch block inside of it to handle that. Everywhere I have looked says that this should be sufficient to catch these async/await promise rejections, but I keep getting an error about an UnhandledPromiseRejection no matter where I throw in a .catch() or try/catch for my code (as suggested in other SO posts).
In this link, for instance, I have pretty much the same thing that is described in the error handling section, but the problem still exists.
https://javascript.info/async-await
Here's the error (I know what is causing the error itself - I have the MongoDB service stopped right now - but I am trying to fix the unhandled promise rejection error):
(node:15633) 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:15633) [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.
(node:13802) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/topologies/server.js:562:11)
at Pool.emit (events.js:189:13)
at Connection.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/pool.js:316:12)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Socket.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/connection.js:245:50)
at Object.onceWrapper (events.js:277:13)
at Socket.emit (events.js:189: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)
and here's my code:
exports.mongoConnect = async (dbName, archiveDbName, userName, password) => {
// Auth params
const user = encodeURIComponent(userName);
const pass = encodeURIComponent(password);
const authMechanism = 'DEFAULT';
// Connection URL
const url = `mongodb://${user}:${pass}#localhost:27017?authMechanism=${authMechanism}&authSource=admin`;
let client;
try {
// Use connect method to connect to the Server
client = await MongoClient.connect(url, { useNewUrlParser: true, poolSize: 10, autoReconnect: true, reconnectTries: 6, reconnectInterval: 10000 }).catch((e) => { console.error(e) });
db = client.db(dbName);
archiveDb = client.db(archiveDbName);
console.log(`Succesfully connected to the MongoDb instance at URL: mongodb://localhost:27017/ with username: "` + client.s.options.user + `"`);
console.log(`Succesfully created a MongoDb database instance for database: "` + db.databaseName + `" at URL: mongodb://localhost:27017/`);
console.log(`Succesfully created a MongoDb database instance for database: "` + archiveDb.databaseName + `" at URL: mongodb://localhost:27017/`);
} catch (err) {
console.log(`Error connecting to the MongoDb database at URL: mongodb://localhost:27017/` + dbName);
}
}
that is being called from app.js like this:
mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'myUser', 'myPassword');
I even tried putting that line in a try/catch block, or adding the promise-style .catch() onto the end of it, with no change.
I can't seem to figure out why it's still complaining about not handling the promise rejection.
EDIT:
Here's the whole app.js file:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var app = express();
const MongoClient = require('mongodb').MongoClient;
// This is where the mongo connection happens
var mongoUtil = require( './services/mongoUtil' );
var bluebird = require('bluebird');
const jwt = require('./helpers/jwt');
var api = require('./routes/api.route')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', api);
// use JWT auth to secure the api
app.use(jwt());
app.use('/users', require('./users/users.controller'));
MongoClient.Promise = bluebird
mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'username', 'password');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;`
I tested your code and it works fine as you can see in the screen shots below. I think the problem lies with whatever is calling mongoConnect()
You are calling connect from app.js in a sync way, So your async/await methods wont work. You can test it using a sleep function:
let sleep = () => {
return new Promise(function(resolve, reject) {
setTimeout(function(){
console.log('Finished sleeping');
resolve();
}, 2000)
})
}
exports.mongoConnect = async (dbName, archiveDbName, userName, password) => {
await sleep() // sleep two seconds
// rest of your mongoConnect code
})
Then add a log in app.js after the connection:
mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'username', 'password');
console.log('Finished connection');
You will obtain the following output in console:
Finished connection // You can see the code doesnt wait to mongo to connect
[After 2 seconds]
Finished sleeping // After this sleep log it will start connecting...
To solve this you would need to execute app.js in an async way:
Be advice top-level async functions are not recommended, but I want you to see the error
(async () => {
// rest of your app.js
await mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'username', 'password');
console.log('Finished connection attempt');
// rest of your app.js
})()
And then the error Im getting at console is (No warnings!):
{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:564:11)
at Pool.emit (events.js:182:13)
at Connection.<anonymous> (/node_modules/mongodb-core/lib/connection/pool.js:317:12)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:246:50)
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)]: {} }
Error connecting to the MongoDb database at URL: mongodb://localhost:27017/myDb
Finished connection attempt
I created the bot with Botact packdge, it running, but I constantly have this error:
**
(node:5744) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
at executionItems.forEach (D:\Node\VK-sleep-bot\node_modules\botact\lib\utils\callbackHandler.js:7:35)
at Array.forEach (<anonymous>)
at module.exports (D:\Node\VK-sleep-bot\node_modules\botact\lib\utils\callbackHandler.js:4:18)
at api.then.catch.err (D:\Node\VK-sleep-bot\node_modules\botact\lib\utils\executeHandler.js:15:23)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
(node:5744) 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)
**
Here my code:
const express = require('express');
const bp = require('body-parser');
const { Botact } = require('botact');
const app = express();
const bot = new Botact({
token: 'c70595eee2bcec797e2e18cb10eab81d46e3ffc68caea34e4d005f231af1c733c751c1ff9cd4908722591',
confirmation: '65a50ccd'})
bot.on(function(ctx){
console.log(ctx.body);
ctx.reply('Hello');
});
app.use(bp.json());
app.post('/', bot.listen);
app.listen(80);
Is anyone know, how I can fix it?