Deploy Node, Express, and MongoDB server to heroku - node.js

I created a server using Node, Express, and MongoDB Atlas. Here is the code of this:
server.js:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
// model
let Cards = require('./models/cards.model');
// App config
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
// DB config
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection has been established successfully.");
})
// API Endpoints
// POST parameter
app.post('/tinder/cards', (req, res) => {
const card = req.body;
Cards.create(card, (err, data) => {
if(err){
return res.status(500).send(err)
} else {
return res.status(200).send(data)
}
})
})
// GET parameter
app.get('/', (req, res) => {
return res.status(200).send("Welcome to Tinder Clone Backend with NodeJS, ExpressJS, and MongoDB!!!")
})
app.get('/tinder/cards', (req, res) => {
Cards.find((err, data) => {
if(err) {
return res.status(500).send(err);
} else {
return res.status(200).send(data)
}
})
});
// Listener
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
});
package.json
{
"name": "tinder-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.12.2"
}
}
cards.model.js
// creating database schema using mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const cardsSchema = new Schema({
name: String,
imgUrl: String
});
const Cards = mongoose.model('Cards', cardsSchema);
module.exports = Cards;
It is working locally and all endpoints sending and receiving data from mongodb atlas.
when I run this command in terminal to start the local server:
$ nodemon server
it is showing this:
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server is running on port 5000
MongoDB database connection has been established successfully.
This means that my local server is running well and when I check in my browser and type in my server link i.e http://localhost:5000/tinder/cards, it showing data that I have posted previously:
[
{
"_id": "605a53881dedb514dcc1c4f2",
"name": "Elon Musk",
"imgUrl": "https://s3.india.com/wp-content/uploads/2020/03/Elon-Musk-AP.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f3",
"name": "Shakira",
"imgUrl": "https://ichef.bbci.co.uk/news/976/cpsprodpb/738B/production/_116497592_gettyimages-971720370.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f4",
"name": "Jeff Bezos",
"imgUrl": "https://media.wired.com/photos/6019cab23453f789506008d0/master/pass/Sec_Bezos_1036084400.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f5",
"name": "Dua Lipa",
"imgUrl": "https://assets.vogue.com/photos/5f48136693122510d16f0352/4:3/w_1080,h_810,c_limit/118520052_586967341971321_6121798062289952442_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f6",
"name": "Pitbull",
"imgUrl": "https://vz.cnwimg.com/wp-content/uploads/2010/03/Pitbull.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f7",
"name": "Ellen",
"imgUrl": "https://www.geo.tv/assets/uploads/updates/2021-03-18/340307_5260100_updates.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f8",
"name": "Bill Gates",
"imgUrl": "https://www.incimages.com/uploaded_files/image/1920x1080/getty_1185999101_20001333200092800_443629.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f9",
"name": "Taylor Swift",
"imgUrl": "https://static.onecms.io/wp-content/uploads/sites/20/2020/12/02/taylor-swift1.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fa",
"name": "Engin Altan",
"imgUrl": "https://www.incpak.com/wp-content/uploads/2020/09/50094085_2224186024567959_693900883193935752_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fb",
"name": "Esra Bilgic",
"imgUrl": "https://i.dawn.com/large/2021/01/6007fbceb61de.png",
"__v": 0
}
]
But when I deployed the same server to heroku, it is showing an empty object when I testing it.
When I run this command into my terminal:
$ heroku logs --tails
It is showing this error:
2021-03-25T11:08:08.715303+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: Could not connect to
any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted.
Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2021-03-25T11:08:08.715323+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:839:32)
2021-03-25T11:08:08.715324+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:348:10
2021-03-25T11:08:08.715326+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
2021-03-25T11:08:08.715326+00:00 app[web.1]: at new Promise (<anonymous>)
2021-03-25T11:08:08.715327+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1152:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:347:20)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:23:10)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1063:30)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:928:32)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:769:14)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at internal/main/run_main_module.js:17:47
2021-03-25T11:08:08.715332+00:00 app[web.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2021-03-25T11:08:08.721117+00:00 app[web.1]: (node:21) 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 term
inate 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)
2021-03-25T11:08:08.721508+00:00 app[web.1]: (node:21) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the fut
ure, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
my server that is deployed on heroku is showing empty object instead of that data that I have posted,
when I type URL of heroku server i.e https://tinder-clone-backend-mern.herokuapp.com/tinder/cards :
{}
How can I make this server work perfectly as the local server does?

Try setting IPS, in your Atlas cluster/Network Access, to be available for all IPS (0.0.0.0/0) Let me know if it fixes.

Related

Discord bot runs on VS Code but crashes on Heroku

I read several StackOverflow posts on similar issues, but I still don't know what to do. I am using Node V16.9.1 and Discord.js V13 Here's my package.json:
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"main": "index.js",
"dependencies": {
"#discordjs/builders": "^0.6.0",
"#discordjs/rest": "^0.1.0-canary.0",
"discord-api-types": "^0.23.1",
"discord.js": "^13.1.0",
"fs-extra": "^10.0.0"
}
}
Here're the files in my project. And here's the Heroku log:
2022-01-10T19:57:45.000000+00:00 app[api]: Build started by user freddyzhang666#gmail.com
2022-01-10T19:58:02.000000+00:00 app[api]: Build succeeded
2022-01-10T19:58:02.088714+00:00 app[api]: Release v4 created by user freddyzhang666#gmail.com
2022-01-10T19:58:02.088714+00:00 app[api]: Deploy 0a32e378 by user freddyzhang666#gmail.com
2022-01-10T19:58:04.138779+00:00 heroku[worker.1]: State changed from crashed to starting
2022-01-10T19:58:06.544367+00:00 heroku[worker.1]: Starting process with command `node index.js`
2022-01-10T19:58:07.235596+00:00 heroku[worker.1]: State changed from starting to up
2022-01-10T19:58:07.912472+00:00 app[worker.1]: (node:4) UnhandledPromiseRejectionWarning: ReferenceError: AbortController is not defined
2022-01-10T19:58:07.912485+00:00 app[worker.1]: at RequestHandler.execute (/app/node_modules/discord.js/src/rest/RequestHandler.js:172:15)
2022-01-10T19:58:07.912485+00:00 app[worker.1]: at RequestHandler.execute (/app/node_modules/discord.js/src/rest/RequestHandler.js:176:19)
2022-01-10T19:58:07.912485+00:00 app[worker.1]: at RequestHandler.push (/app/node_modules/discord.js/src/rest/RequestHandler.js:50:25)
2022-01-10T19:58:07.912486+00:00 app[worker.1]: at async WebSocketManager.connect (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:128:9)
2022-01-10T19:58:07.912486+00:00 app[worker.1]: at async Client.login (/app/node_modules/discord.js/src/client/Client.js:245:7)
2022-01-10T19:58:07.912486+00:00 app[worker.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2022-01-10T19:58:07.912815+00:00 app[worker.1]: (node:4) 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)
2022-01-10T19:58:07.912854+00:00 app[worker.1]: (node:4) [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.
2022-01-10T19:58:07.915370+00:00 app[worker.1]: internal/modules/cjs/loader.js:905
2022-01-10T19:58:07.915371+00:00 app[worker.1]: throw err;
2022-01-10T19:58:07.915372+00:00 app[worker.1]: ^
2022-01-10T19:58:07.915372+00:00 app[worker.1]:
2022-01-10T19:58:07.915374+00:00 app[worker.1]: Error: Cannot find module '/app\anti_negativity.js'
2022-01-10T19:58:07.915375+00:00 app[worker.1]: Require stack:
2022-01-10T19:58:07.915375+00:00 app[worker.1]: - /app/index.js
2022-01-10T19:58:07.915375+00:00 app[worker.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
2022-01-10T19:58:07.915376+00:00 app[worker.1]: at Function.Module._load (internal/modules/cjs/loader.js:746:27)
2022-01-10T19:58:07.915376+00:00 app[worker.1]: at Module.require (internal/modules/cjs/loader.js:974:19)
2022-01-10T19:58:07.915376+00:00 app[worker.1]: at require (internal/modules/cjs/helpers.js:93:18)
2022-01-10T19:58:07.915377+00:00 app[worker.1]: at /app/index.js:13:23
2022-01-10T19:58:07.915377+00:00 app[worker.1]: at Array.forEach (<anonymous>)
2022-01-10T19:58:07.915377+00:00 app[worker.1]: at /app/index.js:11:11
2022-01-10T19:58:07.915378+00:00 app[worker.1]: at /app/node_modules/graceful-fs/graceful-fs.js:209:16
2022-01-10T19:58:07.915378+00:00 app[worker.1]: at FSReqCallback.oncomplete (fs.js:179:23) {
2022-01-10T19:58:07.915378+00:00 app[worker.1]: code: 'MODULE_NOT_FOUND',
2022-01-10T19:58:07.915378+00:00 app[worker.1]: requireStack: [ '/app/index.js' ]
2022-01-10T19:58:07.915379+00:00 app[worker.1]: }
2022-01-10T19:58:08.045930+00:00 heroku[worker.1]: Process exited with status 1
2022-01-10T19:58:08.308457+00:00 heroku[worker.1]: State changed from up to crashed
This is how I load a function from anti_negativity.js; this works perfectly fine on VS Code. The following is from index.js.
const fs = require("fs-extra");
const Discord = require('discord.js');
const client = new Client({ intents: [/* intents not shown */] });
client.commands = new Discord.Collection();
fs.readdir(__dirname, (_err, files) => {
files.forEach(file => {
if (!file.endsWith(".js")) return;
let command = require(__dirname + "\\" + file);
client.commands.set(command.name, command);
});
});
// some code not shown
client.commands.get('anti_negativity').execute(oldMember, newMember, deletionLog.executor);
// some code not shown
client.login(/* token not shown */);
And the following is from anti_negativity.js.
// declarations not shown
module.exports = {
name: 'anti_negativity',
execute(oldMember, newMember, executor) {
// code not shown
}
}
I believe this is the same issue I faced when deploying my first bot to Heroku. If it is then adding
"engines": {
"node": "17.x", // Or your desired version
"npm": "8.x" // Or your desired version
}
or simply
"engines": {
"node": "17.x" // Or your desired version once again
}
to your package.json file should solve the issue.
Hey there!
First of all, if you are using Typescript, whenever you are editing the bot use the command: tsc -w -p . (with the dot). This should be compiling the TypeScript files into JavaScript as you save changes to your files.
Now if you are using JavaScript (this will work with typescript too!) change your packages.json file to this below:
{
"engines": {
"node": "^17.4.0"
},
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"main": "index.js",
"dependencies": {
"#discordjs/builders": "^0.6.0",
"#discordjs/rest": "^0.1.0-canary.0",
"discord-api-types": "^0.23.1",
"discord.js": "^13.1.0",
"fs-extra": "^10.0.0"
}
}
If this doesn't work, replicate your code files on https://codesandbox.io, obviously not putting in the bot token or anything like that and I'll see what I can do!

Teams extension thrwoing UnhandledPromiseRejectionWarning Error: BotFrameworkAdapter.processActivity(): 501 ERROR

I just got started with teams extensions. I modified the code provided by microsoft. My manifest:
...
"composeExtensions": [
{
"botId": "[BOT ID HERE]",
"canUpdateConfiguration": true,
"commands": [
{
"id": "createTimeDisplay",
"type": "action",
"title": "createTimeDisplay",
"description": "Creates a clock showing the given time in the users timezone.",
"initialRun": true,
"fetchTask": true,
"context": [
"commandBox",
"compose",
"message"
],
"parameters": [
{
"name": "param",
"title": "param",
"description": ""
}
],
"taskInfo": {
"title": "Create a new time display",
"width": "medium",
"height": "medium",
"url": "[SOME NGROK PATH HERE]/newTimeDisplay"
}
}
]
} ...
This is my index.js:
// Create bot handlers
const botActivityHandler = new BotActivityHandler();
const server = express();
const port = process.env.port || process.env.PORT || 3978;
server.post('/api/messages', (req, res) => {
console.log("Posted to api/messages/")
adapter.processActivity(req, res, async (context) => {
console.log("processing Activity")
// Process bot activity
await botActivityHandler.run(context);
});
});
server.get('/api/messages', (req, res) => {
console.log("Get to api/messages/")
});
server.listen(port, () =>
console.log(`\Bot/ME service listening at http://localhost:${port}`)
);
console .log("test")
// Listen for incoming requests.
And my botActivityHandler:
class BotActivityHandler extends TeamsActivityHandler {
constructor() {
super();
}
handleTeamsMessagingExtensionSubmitAction(context, action) {
switch (action.commandId) {
case 'createTimeDisplay':
return createTimeDisplay(context, action);
default:
//return createCardCommand(context, action);
console.log("Here")
throw new Error('NotImplemented');
}
}
handleTeamsAppBasedLinkQuery(context, query) {
console.log("look2")
const attachment = CardFactory.thumbnailCard('Thumbnail Card',
query.url,
['https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png']);
const result = {
attachmentLayout: 'list',
type: 'result',
attachments: [attachment]
};
const response = {
composeExtension: result
};
return response;
}
}
function createTimeDisplay(context, action) {
console.log("LOOK!!")
console.log(context)
const heroCard = CardFactory.heroCard("Test", "Me have text");
const attachment = { contentType: heroCard.contentType, content: heroCard.content, preview: heroCard };
return {
composeExtension: {
type: 'result',
attachmentLayout: 'list',
attachments: [
attachment
]
}
};
}
module.exports.BotActivityHandler = BotActivityHandler;
This code results in this error message in the console as soon as I click on the extension in a chat:
test
Bot/ME service listening at http://localhost:3978
Posted to api/messages/
processing Activity
(node:26072) UnhandledPromiseRejectionWarning: Error: BotFrameworkAdapter.processActivity(): 501 ERROR
at BotFrameworkAdapter.<anonymous> (E:\dev\gitgarden\teamsTestApp\What is that in my timezone\node_modules\botbuilder\lib\botFrameworkAdapter.js:741:27)
at Generator.next (<anonymous>)
at fulfilled (E:\dev\gitgarden\teamsTestApp\What is that in my timezone\node_modules\botbuilder\lib\botFrameworkAdapter.js:12:58)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:26072) 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)
(node:26072) [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.
I have no idea what's wrong. Any help/ideas appreciated.

Why are all my Mongoose requests timing out?

My Mongoose requests have all been timing out since yesterday.
My internet connection is working well, the same as usual, and my source code is unchanged.
So, I think it must be a problem with my dependencies or with MongoDB itself.
Minimal reproducible example:
const mongoose = require('mongoose')
const mongoURL = //replace this comment with your own Mongo URL
mongoose.connect(mongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
const exampleSchema = new mongoose.Schema({
title: String,
author: String
})
const Example = mongoose.model('Example', exampleSchema)
const exampleOne = new Example({
title: 'Don Quixote',
author: 'M. Cervantes'
})
exampleOne.save().then(res => console.log(res))
mongoose.connection.close()
Full error trace from running the above example:
(node:18284) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18284) UnhandledPromiseRejectionWarning: MongooseError: Operation `examples.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (G:\Programming\Courses\Fullstack-Helsinki-2020\mongo_testing\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:18284) 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:18284) [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:18284) DeprecationWarning: Listening to events on the Db class has been deprecated and will be removed in the next major version.
My current Mongoose and MongoDB versions (from package.json):
"mongoose": {
"version": "5.11.16",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.11.16.tgz",
"integrity": "sha512-qmolyGAskPuq0Xr3j2Tjm9jwRccGGnLRWtTuyRvYBZoyItajwIoQdetJH8oVzs3N7aZK/GKZ82xV/t97suF8Pg==",
"requires": {
"#types/mongodb": "^3.5.27",
"bson": "^1.1.4",
"kareem": "2.3.2",
"mongodb": "3.6.4",
"mongoose-legacy-pluralize": "1.0.2",
"mpath": "0.8.3",
"mquery": "3.2.4",
"ms": "2.1.2",
"regexp-clone": "1.0.0",
"safe-buffer": "5.2.1",
"sift": "7.0.1",
"sliced": "1.0.1"
},
"dependencies": {
"mongodb": {
"version": "3.6.4",
"resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.6.4.tgz",
"integrity": "sha512-Y+Ki9iXE9jI+n9bVtbTOOdK0B95d6wVGSucwtBkvQ+HIvVdTCfpVRp01FDC24uhC/Q2WXQ8Lpq3/zwtB5Op9Qw==",
"requires": {
"bl": "^2.2.1",
"bson": "^1.1.4",
"denque": "^1.4.1",
"require_optional": "^1.0.1",
"safe-buffer": "^5.1.2",
"saslprep": "^1.0.0"
}
},
"safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
}
}
Question: Why is the above example raising the above error, and, in general, why have my Mongoose requests all been timing out?
First you need to wait a connection to be established to make sure it will be ok, see Error handling:
try {
await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
handleError(error);
}
Second you need to call mongoose.connection.close() after save call will be either resolved or rejected:
exampleOne.save().then(res => {
console.log(res)
mongoose.connection.close()
})
because you didn't use await the save call didn't wait for resolve and mongoose.connection.close() was immediately called.
const res = await exampleOne.save()
console.log(res)
mongoose.connection.close()
})
As I said in comment and also #Anatoly said you should send request (i.e. save) after that connection was established.
const mongoose = require('mongoose')
const exampleSchema = new mongoose.Schema({
title: String,
author: String
})
const Example = mongoose.model('Example', exampleSchema)
const mongoURL = //replace this comment with your own Mongo URL
mongoose.connect(mongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
.then(() => {
const exampleOne = new Example({
title: 'Don Quixote',
author: 'M. Cervantes'
})
exampleOne.save().then(res => {
console.log(res)
mongoose.connection.close()
})
})
.catch(err => {
// handle error
})

TypeError in Discord.JS-Commando Discord Bot

Ok, so I have a bot built in discord.js-commando. I';ve been doing some tweaking to it, mainly trying to add some more functionality, such as logging commands and such to a channel by name as well as adding console.error logging.
Now my attempts to get channel logging are visible in the commands, however the bot keeps throwing a TypeError.... I have no idea what is causing this error or for that matter how to fix it.
Can someone please take a look at my code and help me figure out what is causing the TypeError?
This is the error I keep getting:
console.error
2020-09-30T23:08:24.272196+00:00 app[worker.1]: TypeError: this.commands.filterArray is not a function
2020-09-30T23:08:24.272208+00:00 app[worker.1]: at CommandRegistry.findCommands (/app/node_modules/discord.js-commando/src/registry.js:438:41)
2020-09-30T23:08:24.272208+00:00 app[worker.1]: at CommandDispatcher.matchDefault (/app/node_modules/discord.js-commando/src/dispatcher.js:254:34)
2020-09-30T23:08:24.272209+00:00 app[worker.1]: at CommandDispatcher.parseMessage (/app/node_modules/discord.js-commando/src/dispatcher.js:238:21)
2020-09-30T23:08:24.272209+00:00 app[worker.1]: at CommandDispatcher.handleMessage (/app/node_modules/discord.js-commando/src/dispatcher.js:114:18)
2020-09-30T23:08:24.272210+00:00 app[worker.1]: at CommandoClient.<anonymous> (/app/node_modules/discord.js-commando/src/client.js:68:51)
2020-09-30T23:08:24.272210+00:00 app[worker.1]: at CommandoClient.emit (events.js:315:20)
2020-09-30T23:08:24.272211+00:00 app[worker.1]: at MessageCreateAction.handle (/app/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
2020-09-30T23:08:24.272212+00:00 app[worker.1]: at Object.module.exports [as MESSAGE_CREATE] (/app/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
2020-09-30T23:08:24.272213+00:00 app[worker.1]: at WebSocketManager.handlePacket (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
2020-09-30T23:08:24.272213+00:00 app[worker.1]: at WebSocketShard.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
Here is my main bot file:
index.js
const { Client } = require('discord.js-commando');
const { RichEmbed } = require('discord.js')
const path = require('path');
const prefix = (process.env.BOT_PREFIX);
const twitch_url = (process.env.TWITCH_URL);
const embed_color = (process.env.EMBED_COLOR);
const embed_img = (process.env.EMBED_IMG);
const embed_url = (process.env.EMBED_URL);
const avatar_url = (process.env.AVATAR_URL);
const thumbnail_url = (process.env.THUMBNAIL_URL);
const welcome_channel = (process.env.WELCOME_CHANNEL_NAME);
const member_role = (process.env._MEMBER_ROLE_NAME);
require('dotenv').config();
const client = new Client({
commandPrefix: prefix
})
client.registry
.registerDefaultTypes()
.registerGroups([
['admin', 'Administration'],
['mod', 'Moderation'],
['fun', 'Fun'],
['misc', 'Miscellanious'],
['util', 'Utility']
])
.registerDefaultGroups()
.registerDefaultCommands()
.registerCommandsIn(path.join(__dirname, 'commands'))
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}(${client.user.id})`)
client.user.setActivity(`${prefix}help`, {
type: "STREAMING",
url: twitch_url
})
});
client.on("guildMemberAdd", (member) => {
console.log(`New User "${member.user.username}" has joined "${member.guild.name}"`);
guildMember.addRole(guildMember.guild.roles.find(role => role.name === member_role));
let channel = member.guild.channels.find(c => c.name === welcome_channel);
const embed = new RichEmbed()
.setAuthor("Yuzuki Yukari", avatar_url)
.setUrl(embed_url)
.setColor(embed_color)
.setImage(embed_img)
.setThumbnail(thumbnail_url)
.setFooter("Yuzuki Yukari", avatar_url)
.addField("Welcome", `${member.user.username} has joined ${member.guild.name}`)
return channel.send(embed).catch(console.error);
});
client.on('guildMemberRemove', (member) => {
let channel = member.guild.channels.find(c => c.name === welcome_channel);
const embed = new RichEmbed()
.setAuthor("Yuzuki Yukari", avatar_url)
.setUrl(embed_url)
.setColor(embed_color)
.setImage(embed_img)
.setThumbnail(thumbnail_url)
.setFooter("Yuzuki Yukari", avatar_url)
.addField("Goodbye", `${member.user.username} has left ${member.guild.name}`)
return channel.send(embed).catch(console.error);
});
client.on('error', console.error)
client.login(process.env.BOT_TOKEN);
Here is my package.json file:
package.json
{
"name": "yuzuki",
"version": "1.0.0",
"description": "A Discord Moderation Bot built using Discord.js commando",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "Nimbi",
"license": "ISC",
"dependencies": {
"discord.js": "^12.0.1",
"discord.js-commando": "^0.10.0",
"path": "^0.12.7",
"snekfetch": "^4.0.4",
"sqlite": "^4.0.14",
"uws": "^100.0.1",
"nodemon": "^1.13.3",
"dotenv": "^8.2.0"
},
"engines": {
"node": "^12.0.0"
}
}
My dependencies and their versions can be seen in my package.json, however my node.js version is ^12.0.0, my discord.js version is ^12.0.1, and my discord.js-commando version is ^0.10.0 if that helps.
discord.js-commando#0.10.0 isn't compatible with discord.js#12. It's package.json specifies that Discord.js ^11.2.0 must be used.
The error is because Collection#filterArray was removed in v12, and therefore this.commands.filterArray is undefined and not a function in the Commando code.
You have 2 options:
Downgrade to Discord.js v11.
Use the master branch of discord.js-commando, which is compatible with Discord.js v12. However, this branch may be unstable and/or have bugs.
To use this, change "discord.js-commando": "^0.10.0" in your package.json to "discord.js-commando": "discordjs/Commando". See GitHub URLs in npm's package.json documentation for more details on this.

Electron with strapi, Cannot find module package.json

I built an application using strapi, i am trying to package it inside electron using electron-builder.
The packaging is done well, but when i start the app, it shows this message
PS E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked>
(node:13196) UnhandledPromiseRejectionWarning: Error: Cannot find module 'E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\package.json'
Require stack:
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\index.js
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\index.js
-
at Module._resolveFilename (internal/modules/cjs/loader.js:797:17)
at Function.o._resolveFilename (electron/js2c/browser_init.js:281:679)
at Module._load (internal/modules/cjs/loader.js:690:27)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at new Strapi (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js:94:21)
at module.exports (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js:564:18)
at createWindow (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\index.js:23:5)
(node:13196) 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:13196) [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.
What seems to be the problem is that my application is looking to package.json file inside the root folder (directly relative to the exe file), while it exist inside the (app) folder with all other resources of the system.
this is my package.json file
{
"name": "DentalSys",
"main": "./index.js",
"version": "0.2.0",
"description": "Dental Clinic Management System",
"productName": "DentalSys",
"build": {
"appId": "com.kldoon.dentalSys",
"asar": false
},
"scripts": {
"develop": "strapi develop",
"strapi-start": "strapi start",
"strapi-prod": "cross-env NODE_ENV=production npm start",
"strapi-build": "strapi build",
.....
},
"devDependencies": {
"concurrently": "^5.1.0",
"electron": "^9.1.2",
"electron-builder": "^22.4.1",
......
},
"dependencies": {
"knex": "0.20.13",
"moment": "^2.27.0",
"sqlite3": "^4.1.1",
"strapi": "3.0.0-beta.17.5",
.......
}
And this is my electron (index.js) file
const { app, BrowserWindow, Menu, dialog } = require('electron')
const path = require("path");
const strapi = require('strapi');
//const { exec } = require("child_process");
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
maximizable: true,
title: "Dental System",
webPreferences: {
nodeIntegration: true
}
})
win.maximize();
strapi().start().then(() => {
win.loadURL('http://localhost:49862/');
}).catch((e) => {
console.log(e);
});
win.on('closed', () => {
app.quit();
})
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
I tried multiple solutions but none work, i hope someone can help with it.
Thanks in advance.
It turned out to be easy fix, with dir option of strapi constructor
strapi({
dir: __dirname + '/' ///<==== add this
}).start().then(() => {
win.loadURL('http://localhost:1337/');
}).catch((e) => {
dialog.showMessageBox(win, { message: JSON.stringify(e) });
console.log(e);
});

Resources