Hi everyone i try to pass some images to my firebase with Functions but when i deploy firebase(with cli firebase deploy)inside my terminal i got an error and the deploy abort.
Apparently the error say my require inside function/index.js is not a function (line 9 col 45) but the gcconfig was do with the right method for me.
I want to correctly deploy firebase from CLI.
The error from cli firebase deploy i got on my terminal:
Error: Error occurred while parsing your function triggers.
TypeError: require(...) is not a function
at Object.<anonymous> (/Users/luca/Code/Code_Taff/Benibla/bnblproto/functions/index.js:9:45)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:15:15
at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:53:3)
function/index.js:
const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
const fs = require('fs');
const UUID = require("uuid-v4");
const gcconfig = {
projectId: "beniblaproto",
keyFilename: "beniblaproto.json"
};
const gcs = require("#google-cloud/storage")(gcconfig);
exports.storeImage = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
const body = JSON.parse(request.body);
fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
console.log(err);
return response.status(500).json({error: err});
});
const bucket = gcs.bucket("beniblaproto.appspot.com");
const uuid = UUID();
return bucket.upload(
"/tmp/uploaded-image.jpg",
{
uploadType: "media",
destination: "/events/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "image.jpg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, file) => {
if (!err) {
response.status(201).json({
imageUrl: "https://firebasestorage.googleapis.con/v0/b" +
bucket.name +
"/o/" +
encodeURIComponent(file.name) +
"?alt=media&token=" +
uuid
});
} else {
console.log(err);
response.status(500).json({error: err});
}
}
);
});
});
if someone can explain me where and for what i fail.
Thank you all have a good day
Firstly you need to import {Storage} of library;
const {Storage} = require("#google-cloud/storage");
after that you need to take an instance with your configuration object;
const gcs = new Storage(gcconfig);
Related
I am currently working on a React-app front-end for Amazon AWS S3. The goal of the project is to allow a user to upload multiple images to a S3 bucket, and then call a Lambda function to send the uploaded images to Amazon Rekognition for labeling. The results will then be returned in a CSV file that the user can download as the output.
However, I am currently encountering an issue where I am getting the following error message:
Failed to compile.
export 'downloadCSV' (reexported as 'downloadCSV') was not found in './rekognitionActions' (possible exports: addFacesToCollection, createCollection, detectLabels, getLabeledResults, handleFileUpload, indexFaces, parseCSV, searchFaces, searchFacesByImage, uploadImages, uploadImagesAndGetLabels)
ERROR in ./src/components/actions/index.js 5:0-84
export 'downloadCSV' (reexported as 'downloadCSV') was not found in './rekognitionActions' (possible exports: addFacesToCollection, createCollection, detectLabels, getLabeledResults, handleFileUpload, indexFaces, parseCSV, searchFaces, searchFacesByImage, uploadImages, uploadImagesAndGetLabels)
ERROR in ./src/components/actions/rekognitionActions.js 4:0-38
Module not found: Error: Can't resolve 'fs' in 'C:\Users\luisj\Desktop\awsapp\awsapp\src\components\actions'
I am also receiving
Module not found: Error: Can't resolve 'fs' in 'C:\Users\luisj\Desktop\awsapp\awsapp\src\components\actions'
I am unsure of what is causing this issue and would greatly appreciate any help in resolving it.
rekognitionActions.js
import AWS from 'aws-sdk';
import { createReadStream } from 'fs';
import Papa from 'papaparse';
const rekognition = new AWS.Rekognition({
accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY,
});
const s3 = new AWS.S3({
accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY,
});
export const detectLabels = async (image) => {
const params = {
Image: {
S3Object: {
Bucket: process.env.REACT_APP_AWS_S3_BUCKET,
Name: image,
},
},
MaxLabels: 10,
MinConfidence: 80,
};
const data = await rekognition.detectLabels(params).promise();
return data.Labels;
};
export const createCollection = async (collectionId) => {
const params = {
CollectionId: collectionId,
};
await rekognition.createCollection(params).promise();
};
export const indexFaces = async (collectionId, image) => {
const params = {
CollectionId: collectionId,
Image: {
S3Object: {
Bucket: process.env.REACT_APP_AWS_S3_BUCKET,
Name: image,
},
},
};
const data = await rekognition.indexFaces(params).promise();
return data.FaceRecords;
};
export const searchFacesByImage = async (collectionId, image) => {
const params = {
CollectionId: collectionId,
Image: {
S3Object: {
Bucket: process.env.REACT_APP_AWS_S3_BUCKET,
Name: image,
},
},
MaxFaces: 10,
FaceMatchThreshold: 80,
};
const data = await rekognition.searchFacesByImage(params).promise();
return data.FaceMatches;
};
export const uploadImages = async (images) => {
const uploadPromises = images.map(async (image) => {
const params = {
Bucket: process.env.REACT_APP_AWS_S3_BUCKET,
Key: image.name,
Body: image,
};
await s3.upload(params).promise();
});
await Promise.all(uploadPromises);
};
export const getLabeledResults = async (images) => {
const labelPromises = images.map(async (image) => {
const labels = await detectLabels(image.name);
return { imageName: image.name, labels };
});
const labeledResults = await Promise.all(labelPromises);
return labeledResults;
};
export const uploadImagesAndGetLabels = async (images) => {
await uploadImages(images);
const labeledResults = await getLabeledResults(images);
return labeledResults;
};
export const parseCSV = async (file) => {
return new Promise((resolve, reject) => {
Papa.parse(createReadStream(file), {
header: true,
complete: (results) => {
resolve(results.data);
},
error: (error) => {
reject(error);
},
});
});
};
export const addFacesToCollection = async (collectionId, images) => {
const indexFacePromises = images.map(async (image) => {
const indexedFaces = await indexFaces(collectionId, image.name);
return { imageName: image.name, indexedFaces };
});
const indexedResults = await Promise.all(indexFacePromises);
return indexedResults;
};
export const searchFaces = async (collectionId, images) => {
const searchFacePromises = images.map(async (image) => {
const faceMatches = await searchFacesByImage(collectionId, image.name);
return { imageName: image.name, faceMatches };
});
const searchResults = await Promise.all(searchFacePromises);
return searchResults;
};
export const handleFileUpload = async (file, collectionId) => {
try {
const images = await parseCSV(file);
await uploadImagesAndGetLabels(images);
await createCollection(collectionId);
const indexedResults = await addFacesToCollection(collectionId, images);
const searchResults = await searchFaces(collectionId, images);
return { indexedResults, searchResults };
} catch (error) {
throw error;
}
};
index.js
import * as rekognitionActions from './rekognitionActions';
import * as otherActions from './otherActions';
import { uploadImages, getLabeledResults, downloadCSV } from './actions';
export const { uploadImages, getLabeledResults, downloadCSV } = rekognitionActions;
export const { otherAction1, otherAction2 } = otherActions;
I have made my full project available on my GitHub repository, which can be accessed HERE
I am trying to create a React-app front-end for Amazon AWS S3. The goal of this project is to allow a user to upload multiple images to a S3 bucket, and then call a lambda function to send the uploaded images to Amazon Rekognition for labeling. The results are then returned in a CSV file that the user can download as the output.
I have created the necessary components and actions for this project, but when I try to compile the code, I am getting an error :
Module not found: Error: Can't resolve './components/actions' in 'C:\Users\luisj\Desktop\awsapp\awsapp\src\components'". I am also getting an error that says "export 'downloadCSV' (reexported as 'downloadCSV') was not found in './rekognitionActions' (possible exports: addFacesToCollection, createCollection, detectLabels, getLabeledResults, handleFileUpload, indexFaces, parseCSV, searchFaces, searchFacesByImage, uploadImages, uploadImagesAndGetLabels)". Additionally, there is an error that says "Module not found: Error: Can't resolve 'fs' in 'C:\Users\luisj\Desktop\awsapp\awsapp\src\components\actions'
I was expecting the code to compile without any errors, and for the application to function as intended. However, the errors I am receiving are preventing me from moving forward with the project.
I have tried re-organizing the file structure, double checking the imports and exports in the code, and making sure that all necessary dependencies are installed, but I am still encountering these errors.
I recently started working on discord ban bot with 3 main features:
Export IDs of all banned users in current Server/Guild.
Import IDs of banned users into current guild
Transfer ban list from current server to target server. (Under development)
None of the slash commands are working even though the logic is seemingly correct.
I'm following the discordjs guide & managed to make a Time Tag generator bot & this is my 2nd bot project. I admit I'm not familier with Javascript but the guide is very helpful nonetheless
Here is the export-ban-list code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
function new_paste(serverName, results) {
const outputFile = `${serverName}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return data;
}
else {
return 'There was some unexpected error.';
}
});
}
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
const fe = new_paste(interaction.serverName, results);
return interaction.editReply(fe);
},
};
This command basically calculates the number of users banned, makes an array & exports it to pastebin.
The issue is, the bot code reaches till calculation part, but when it comes to making the list, console throws me errors:
Found 13 bans. Exporting...
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async InteractionWebhook.editMessage (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\Webhook.js:311:15)
at async CommandInteraction.editReply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:137:21)
at async Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:41:3) {
method: 'patch',
path: '/webhooks/897454611370213436/aW50ZXJhY3Rpb246ODk4ODkyNzI0NTcxMzczNjA5OmtPeGtqelQ5eUFhMnNqVzc1Q3BpMWtQZUZRdVhveGQxaHFheFJCdVFoUWNxNUk5TVpGbThEQjdWcDdyaHZyaUJPeUpsRWFlbUp0WnVLYjB5V0RtYmJCSmlNU2wwUVlka1hYMHg0bHRJbzlHelVwRmJ6VUpRaXF2YktaVDN1ZlVp/messages/#original',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at CommandInteraction.reply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89:46)
at Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:45:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
Thanks to Jim I used the console.log() to check what was going on.
And indeed the data from function inside new_paste() wasn't being returned to fe.
(I had messed up the return scopes basically)
Here is the final code after fixes & scope resolutions
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
console.log(results);
const outputFile = `${interaction.guild.name}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return interaction.editReply(data);
}
else {
return interaction.editReply('There was some unexpected error.');
}
});
},
};
And finally I get the proper pastebin url as output.
Code hosted here
I think your npm package better-pastebin has an error. I am not familiar with that npm package, so I can’t determine whether it has an error for you, but I think if you change the npm package, the error will not appear.
I'm getting the following error in my react application using enigma.js (https://qlik.dev/apis/javascript/enigmajs) . I'm trying to initialize a WebSocket connection and im getting the error. "Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid".
The WebSocket connection URL is correct as it can be tested with https://catwalk.core.qlik.com/?engine_url=wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde which returns the data. You can try by editing the URL which will return an error.
the code is
async init() {
const appId = "133dab5d-8f56-4d40-b3e0-a6b401391bde";
const url =
"wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde";
const session = enigma.create({
schema,
createSocket: () =>
new WebSocket(url, {
}),
});
const global = await session.open();
const app = await global.openDoc(appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
I found the solution:
qDoc.config.js
const enigma = require('enigma.js');
const schema = require('enigma.js/schemas/12.20.0.json');
const SenseUtilities = require('enigma.js/sense-utilities');
const config = {
host: 'sense-demo.qlik.com',
secure: true,
port: 443,
prefix: '',
appId: '133dab5d-8f56-4d40-b3e0-a6b401391bde',
};
const url = SenseUtilities.buildUrl(config);
async function init() {
const session = enigma.create({
schema,
url,
suspendOnClose: true,
});
const global = await session.open();
const app = await global.openDoc(config.appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
init();
const session = enigma.create({ schema, url, suspendOnClose: true });
// open doc and return promise which will resolve to doc
export const openDoc = () => (
session.open().then((global) => global.openDoc(config.appId))
);
// close session
export const closeSession = () => (
session.close()
);
INSTURCTION
downoad this project
delete package-lock.json file
npm i
npm run-script dev
This is the direvtory view:
This is result log:
The solution is explained here
https://github.com/qlik-oss/enigma.js/issues/889
Server is starting at 8080
GET / 304 - - 1.952 ms
(node:6139) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: bad auth Authentication failed.
at new MongooseServerSelectionError (/Users/abc/Desktop/success/node_modules/mongoose/lib/error/serverSelection.js:22:11)
at NativeConnection.Connection.openUri (/Users/abc/Desktop/success/node_modules/mongoose/lib/connection.js:808:32)
at Mongoose.connect (/Users/abc/Desktop/success/node_modules/mongoose/lib/index.js:333:15)
at Object. (/Users/abc/Desktop/success/pages/server.js:18:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:6139) 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:6139) [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.
GET / 304 - - 0.320 ms
GET / 304 - - 0.236 ms
GET / 304 - - 0.210 ms
When I run Port 8080 for my serverjs, the file works but no data gets into my mongoDB and I get the above error on my terminal. I only have a server.js page and an index.tsx page. My index.tsx page has a simple Hello world and I am trying to connect Mongodb using the server.js file.
Here is my code:
import express from 'express';
import { connect, connection, Schema as _Schema, model } from 'mongoose';
import morgan from 'morgan';
import path from 'path';
const app = express();
const PORT = process.env.PORT || 8080;
//Success
const MONGODB_URI = 'mongodb+srv://xxxxxxxxxx';
mongoose.connect(MONGODB_URI || 'mongodb://localhost/success', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
})
//Schema
const Schema = _Schema;
const BlogPostSchema = new Schema({
title: String,
body: String,
date: {
type: String,
default: Date.now()
}
});
//Model
const BlogPost = model('BlogPost', BlogPostSchema);
//Saving data to our mongoDB
const data = {
title: 'welcome',
body: 'first post'
};
const newBlogPost = new BlogPost(data);
newBlogPost.save((error) => {
if (error) {
console.log("Somethign happened");
} else {
console.log("data saved");
}
});
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
I think it's because mongoose.connect is asynchronous(not very clear from the documentation). Try putting your code within the "connected" event and see if it works:
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
//Schema
const Schema = _Schema;
const BlogPostSchema = new Schema({
title: String,
body: String,
date: {
type: String,
default: Date.now()
}
});
//Model
const BlogPost = model('BlogPost', BlogPostSchema);
//Saving data to our mongoDB
const data = {
title: 'welcome',
body: 'first post'
};
const newBlogPost = new BlogPost(data);
newBlogPost.save((error) => {
if (error) {
console.log("Somethign happened");
} else {
console.log("data saved");
}
});
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
})
const express=require('express');
const mongoose=require('mongoose');
const morgan=require('morgan');
const path=require('path');
const app = express();
const PORT = process.env.PORT || 8080;
mongoose.connect('mongodb://localhost/SUCCESS', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
})
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
node pages/server.js
Server is starting at 8080
(node:6253) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at new MongooseServerSelectionError (/Users/Abc/Desktop/success/node_modules/mongoose/lib/error/serverSelection.js:22:11)
at NativeConnection.Connection.openUri (/Users/Abc/Desktop/success/node_modules/mongoose/lib/connection.js:808:32)
at Mongoose.connect (/Users/Abc/Desktop/success/node_modules/mongoose/lib/index.js:333:15)
at Object.<anonymous> (/Users/Abc/Desktop/success/pages/server.js:18:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:6253) 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:6253) [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 had the same issue. Please update your code like this.
mongoose.connect("mongodb://127.0.0.1:27017/SUCCESS",{
useCreateIndex:true,
useNewUrlParser: true,
useUnifiedTopology: true}).then(()=> {
console.log('Database Successfully Connected')},error =>{
console.log(error)})
As next step,
Go to your Task Manager
Services
Start 'MongoDB'
Hope this will work.
// Seems like you did not define the default port of mangoose, Please refer below code
const mongoose = require('mongoose');
const db = "mongodb://localhost:27017/SUCCESS";
mongoose.connect(db, {
useCreateIndex:true,
useUnifiedTopology:true,
useNewUrlParser:true
}).then( () => {
console.log("Connected To Mongo Db DataBase");
}).catch((err) => {
console.log("DataBase Connection Error " + err);
})
I know I'm super late but this should fix it.
const db = mongoose.connect("mongodb://localhost/swag-shop",
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
}).then(() => {
console.log("Connected To Mongo Db DataBase");
}).catch((err) => {
console.log("DataBase Connection Error " + err);
});
then go to your powershell in windows or terminal in mac and type 'Mongod' and then create another tab in your terminal or open a another window of powershell and then type 'Mongo' and this should fix your problem.