crbug/1173575, non-JS module files deprecated VM10:6747 - mongodb

Hello I am super new to web development, currently doing the udemy bootcamp. I was working on my app and everything was fine but suddenly my browser stopped rendering and I got this error:
VM10:6747 crbug/1173575, non-JS module files deprecated.
Got the error even though it shows in my terminal that the database is connected and working. I googled and youtubed this problem but none of the solutions online seem to work. I am using VSC and I went ahead and deleted the launch.json file but that didnt work either. Any other suggestions would really be appreciated. Is there anything within my code that can produce this error? Here is my app.js in case I am missing something.
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const ejsMate = require('ejs-mate'); //this is an engine use to parse ejs
const session = require('express-session');
const flash = require('connect-flash');
const ExpressError = require('./utils/ExpressError');
const methodOverride = require('method-override');
//requiring routes
const campgrounds = require('./routes/campgrounds');
const reviews = require('./routes/reviews');
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/yelp-camp', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("Database connected")
})
.catch(err => {
console.log("Database not connected")
console.log(err)
});
const app = express();
app.engine('ejs', ejsMate); //here we are telling express to use the engine we selected instead of the default one
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true })); //to help us parse the req.body
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash);
const sessionConfig = {
secret: 'thisshouldbeabettersecret',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true, //this is a security item
expires: Date.now() + 1000 * 60 * 60 * 24 * 7, //date.now is in miliseconds. the numbers after are a multiplication = to a week
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig));
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
});
app.use('/campgrounds', campgrounds);
app.use('/campgrounds/:id/reviews', reviews);
app.get('/app', (req, res) => {
// res.send('hello! working on your request')
res.render('home')
})
// HOME PAGE
app.get('/', (req, res) => {
res.send('HOMEPAGE!');
})
//ERROR MIDDLEWARE
app.all('*', (req, res, next) => {
next(new ExpressError('Page not found', 404))
}) //this selects all and if nothing else wrongs this will.
app.use((err, req, res, next) => {
const { statusCode = 500 } = err; //here we are deconstructing our expresserror and then sending the message
if (!err.message) err.message = 'Oh no, Something Went Wrong';
res.status(statusCode).render('error', { err })
})
app.listen(3000, () => {
console.log("Serving in port 3000")
})

Nevermind! Found the error.
Had:
app.use(flash)
Instead of:
app.use(flash())

Related

Next.js and Mongoose and Passport.js: req.user is undefined

I am using the relatively newer setup with Next.js API routes, this doesn't use express but instead the API setup to create your routes to an endpoint.
My problem is I'd like to have a route called api/user which will return the user i.e. req.user:
The following comes from with-passport-and-next-connect
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
if (req.session.user) {
const { _id } = req.session.user
res.json({ user: { _id } })
} else {
res.json({ user: null })
}
})
export default handler
That file references this auth file:
import nextConnect from 'next-connect'
import passport from '../lib/passport'
import session from '../lib/session'
const auth = nextConnect()
.use(
session({
name: 'sess',
secret: process.env.TOKEN_SECRET,
cookie: {
maxAge: 60 * 60 * 8, // 8 hours,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
},
})
)
.use((req, res, next) => {
// Initialize mocked database
// Remove this after you add your own database
req.session.users = req.session.users || []
next()
})
.use(passport.initialize())
.use(passport.session())
export default auth
I have added this in my version:
.use((req, res, next) => {
connectDB()
next()
})
But that yields nothing.
In api/login I added this line
req.session.user = req.user;
after the authenticate function. But that doesn’t add the user to the session object.
handler
.use(auth)
.post((req, res, next) => {
emailValidator(req, res, next, 'email', 'password');
},
async (req, res, next) => {
await connectDB();
passport.authenticate('local', (err, user, info) => {
req.session.user = req.user;
Could anyone please help me with this?
Thanks in advance.

Setup error handlers in express/mongoose/mongoDB

I'm currently part of a web dev Bootcamp and my current project is requesting I create error handlers in a specific manner that I do not understand. Below is a screenshot of the directions . . .
Here are my current files in hopes that it makes sense . . .
/* app.js */
const express = require('express');
const mongoose = require('mongoose');
const userRouter = require('./routes/users');
const cardRouter = require('./routes/cards');
const { PORT = 3000 } = process.env;
const app = express();
mongoose.connect('mongodb://localhost:27017/aroundb', {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
});
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
req.user = { _id: '60c4e0e2a80be4c8c2de5474' };
next();
});
app.use('/users', userRouter);
app.use('/cards', cardRouter);
app.listen(PORT, () => logMsg(`listening on port ${PORT} . . .`));
/* routes/users.js */
const express = require('express');
const { getUsers, getUser, createUser } = require('../controllers/users');
const router = express.Router();
router.get('/', getUsers);
router.get('/:id', getUser);
router.post('/', createUser);
module.exports = router;
/* controllers/users.js */
const User = require('../models/user');
module.exports.getUsers = (req, res) => {
User.find({})
.then((users) => res.status(200).send({ data: users }))
.catch((err) => res.status(500).send({ message: err }));
};
module.exports.getUser = (req, res, next) => {
User.findById(req.params.id)
.then((user) => res.send({ data: user }))
.catch((err) => res.status(404).send({ message: err }));
};
module.exports.createUser = (req, res) => {
const { name, about, avatar } = req.body;
User.create({ name, about, avatar })
.then((user) => res.status(201).send({ data: user }))
.catch((err) => res.status(400).send({ message: err }));
};
My questions are:
Where should the code example provided (in the screenshot) go? Am I creating a separate controller or middleware? Or maybe it goes in the already coded controller?
Would I be creating my own errors and using a conditional to read the message?
I already thought I was handling errors, as seen in controllers/users.js, is that not the case?
NOTE: My apologies, I know that since it's from a course it might not make sense outside the context of the lesson(s). I also know there are various ways projects can be coded/solved. Unfortunately, my Bootcamp does not have live instruction, just a slack channel where 97% of responses come from Alumni. Please do not hesitate to ask questions that may help clarify things.
It seems you're directly sending an error in the last two cases, without knowing which type of it is, however it looks fine for fetching all users (1st case).
The workaround that might help you is,
Get user :
User.findById(req.params.id), function(err, user) {
if(err) {
return res.status(500).send({ message: "Default error" });
} else if (!user) {
return res.status(404).send({ message: "User not found" });
}
}
For creating a user you need to manually verify all the fields that are required in schema for ex.,
createUsers : {
const { name, about, avatar } = req.body;
if (name === null || about === null || avatar === null) {
return res.status(400).send({
message : "Required data missing in request"
})
}
... // create user
}

Import CSV file data into MongoDB using mongoose

I am building a full-stack application using MERN(MongoDB, Express, React, Node.js).
I have a .CSV file that I uploaded to MongoDB. However I can't get my routes to return any data.
I can see the database collection on my MongoDB cluster, But it's not showing up in my mongo shell.
My thought process is that's why I can't get my routes to work. How can I fix that?
sample .csv file data
Date,Client,Project,Project Code,Hours,Billable?,First Name,Last Name,Billable Rate
,,,,,,,,
4/3/17,Anil,Ethereum,RD001,3.84,No,Robert,Powell,0
4/3/17,Olith,Pharos,DV002,7.69,Yes,Hubert,Green,80
4/3/17,Olith,Pharos,DV002,4.46,Yes,Bradley,Hale,80
4/3/17,Olith,Pharos,DV002,7.57,Yes,Rudy,Parker,80
4/3/17,Prosaria,Business Development,GM001,0.92,No,Walter,Silva,0
As you can see the data exists in my mongo-atlas
But my mongo-shell is empty when I call db.clients.find()
server.js
const express = require('express');
const app = express();
const mongodb = require('mongodb').MongoClient;
const fs = require('fs');
const fastcsv = require('fast-csv');
const csvtojson = require('csvtojson');
require("dotenv").config()
const PORT = process.env.PORT || 3003;
//middleware
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(express.static(__dirname + 'public'));
// Global Configuration
const MONGODBURI = process.env.MONGODBURI || 'mongodb://localhost:27017/projectData';
let stream = fs.createReadStream('./gm_data.csv');
let csvData = [];
let csvStream = fastcsv
.parse()
.on('data', (data) => {
csvData.push({
date: data[0],
client: data[1],
project: data[2],
projectCode: data[3],
hours: data[4],
billable: data[5],
firstName: data[6],
lastName: data[7],
billableRate: data[8]
})
})
.on('end', () => {
csvData.shift();
console.log(csvData);
mongodb.connect(
MONGODBURI, {
useNewUrlParser: true,
useUnifiedTopology: true
},
(err, client) => {
if (err) throw err;
client
.db('gm-clients')
.collection('clients')
.insertMany(csvData, (err, res) => {
if (err) throw err;
console.log(`Inserted: ${res.insertedCount} rows`);
client.close
});
}
);
});
stream.pipe(csvStream);
//TEST ROUTE --- // http://localhost:3003/
app.get('/', (req, res) => {
res.send('Say Hello to Zee Server')
})
//routes
const customerRoutes = require('./routes/routes.js');
app.use('/customer', customerRoutes);
//Listening
app.listen(PORT, () => {
console.log('Listening on port', PORT)
})
routes.js
const express = require('express')
const router = express.Router();
const path = require('path');
let fs = require('fs');
let parse = require('csv-parse');
const csv = require('csvtojson');
const Customer = require('../models/customer.js');
//Index Route -- //http://localhost:3003/customer/allcustomers
router.get('/allcustomers', (req, res) => {
Customer.find({}, 'client', (err, data) => {
res.json({data: data});
})
})
module.exports = router;
models.js
const mongoose = require('mongoose')
const customerSchema = new mongoose.Schema({
name: String, //project col in CSV
clients: String, //client col in csv
hours: Number, // hours col in csv
billable_hours: Number, // billable col in csv
billable_amount: Number // billable rate in csv
})
// name | clients | hours | billable hours | billable amount
module.exports = mongoose.model('Customer', customerSchema);

Socket.io, Mongodb returning undefined to frontend

I want to use socekt.io for a new project I am building. I am using socket.io for a login component and will be using socket.io in the future to update pages like a chat app. I am also using mongoose to handle my mongodb connection. I am taking in a username, and returning a password to my front end to be bcryptjs compareSync hashed. The problem I am having is that whatever is returned to the front end is undefined. When I print out what is returned to the front end, it prints out the value I am looking for though. Something is going on between the backend emitting something, and the frontend receiving something but I don't know what is it exactly. Here is my code for the back end:
const express = require('express')
const socket = require('socket.io');
const http = require('http');
const router = require('./router');
const mongoose = require('mongoose');
let Player = require('../models/player.model');
require('dotenv').config();
const PORT = process.env.PORT || 5000;
const app = express();
const server = http.createServer(app);
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 established successfully')
});
const io = socket(server);
io.on('connection', (socket) => {
console.log('We have a new connection');
socket.on('login', ({ username }, callback) => {
console.log(username);
Player.find({"username": username}, function (err, player) {
if(err) {
console.log("there has been an error"), {player: null}
}
socket.emit('id', { password: player[0]['password'].toString(), id : player[0]['_id']})
}) })})
app.use(router);
server.listen(PORT, () => console.log('Server is working'))
Here is my code for the front end:
const ENDPOINT = 'localhost:5000';
async function submitAccount (e) {
e.preventDefault();
socket.emit('login', { username });
socket.on("id", (response) => {
setPassword2(String(response['password']));
id = response['id']; console.log(id);
console.log(password2)
});
try {
if (bcrypt.compareSync(password, password2) == true) {
props.setCookie("id", id);
setAccess(true);
access2 = true;
console.log(access2)
console.log('works')
}
else {
setErrorType('Invalid Password')
setErrorMsg('There is an issue with your password. Please try again')
setOpenModal(true)
console.log(password);
console.log(password2);
}
}
catch {
setErrorType('Invalid Username')
setErrorMsg('This username does not exist. Please try another')
setOpenModal(true)
}
Thanks for the help!
When you do the socket.on, it should include the whole statement you are looking to change with the socket.io output. See below:
async function submitAccount (e) {
e.preventDefault();
socket.emit('login', { username });
socket.on("id", (response) => {
setPassword2(String(response['password']));
id = response['id']; console.log(id);
console.log(password2)
if (password2 != undefined) {
try {
if (bcrypt.compareSync(password, password2) == true) {
props.setCookie("id", id);
setAccess(true);
access2 = true;
console.log(access2)
console.log('works')
}
}

Mongoose save() does not work when putting documents in collection and uploading files using multer-gridfs-storage

I am trying to build a music app and while working on the back end for the app (using express), I am facing this weird issue of documents not saving in mongo collections.
I made a post route to which user submits form data, which contains the song's mp3 file and the name of the song (it will have more data later on).
I am using multer to parse multipart form data.
I am able to save the mp3 file to mongoDB using multer-gridfs-storage. I want to save the song info such as name, artists etc in a different collection and here is the schema for the collection:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const SongsInfo = new Schema({
name: {
type: String,
required: true,
},
});
const Song = mongoose.model('Song', SongsInfo);
export default Song;
index.js file:
import Grid from 'gridfs-stream';
import GridFsStorage from 'multer-gridfs-storage';
const app = express();
const conn = mongoose.createConnection(mongoURI);
let gfs;
conn.once('open', () => {
console.log('Connected to mongodb');
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('songFiles');
});
// storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') +
path.extname(file.originalname);
let fileInfo;
fileInfo = {
filename,
bucketName: 'songFiles',
};
resolve(fileInfo);
});
}),
});
let upload;
middleWare(app);
app.post('/api/uploadSong', async (req, res) => {
upload = multer({ storage }).any();
upload(req, res, async (err) => {
console.log('in');
if (err) {
// console.log(err);
return res.end('Error uploading file.');
}
const { name } = req.body;
// push a Song into songs collection
const songInfo = new Song({
name,
});
const si = await songInfo.save(); // (*)
console.log(songInfo);
res.json({
songInfo: si,
file: req.file,
});
});
});
On line (*) the server just freezes until the request gets timed out.
No errors shown on console. Don't know what to do :(
I solved the issue finally!
So what i did was bring the models in index.js file and changed up some stuff here and there..
index.js
const app = express();
mongoose.connect(mongoURI); //(*)
const conn = mongoose.connection; // (*)
let gfs;
conn.once('open', () => {
console.log('Connected to mongodb');
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('songFiles');
});
// models
const Schema = mongoose.Schema; //(***)
const SongsInfo = new Schema({
name: {
type: String,
required: true,
},
});
const Song = mongoose.model('Song', SongsInfo);
// storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
let fileInfo;
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
fileInfo = {
filename,
bucketName: 'imageFiles',
};
} else {
fileInfo = {
filename,
bucketName: 'songFiles',
};
}
resolve(fileInfo);
});
}),
});
let upload;
middleWare(app);
app.post('/api/uploadSong', async (req, res) => {
upload = multer({ storage }).any();
upload(req, res, async (err) => {
console.log('in');
if (err) {
return res.end('Error uploading file.');
}
const { name } = req.body;
// push a Song into songs collection
const songInfo = new Song({
name,
});
songInfo.save((er, song) => {
if (!er) {
res.send('err');
} else {
console.log(err, song);
res.send('err');
}
});
});
});
At line (***) I used the same instance of mongoose that was initialized.. in the previous file I imported it again from the package...
Kia ora!
For those stumbling here three years on. I came across this issue as well. Abhishek Mehandiratta has the answer hidden in their code snippet.
The Fix
I went from instantiating mongoose with:
connect(connStr)
to doing:
const conn = createConnection(connStr)
This is the breaking change. So for an easy fix, change your code back to using connect(...).
I too, followed the documentation and Youtube tutorials to alter my code in such a way. It's an unfortunate misleading for developers who have not encountered a need to understand the difference.
I changed it back, and now it's working again (even with 'multer-gridfs-storage'). You can reference the connection with:
import {connection} from "mongoose";
connection.once('open', ...)
Why is this happening?
BenSower writes up the differences between connect and createConnection here. So from my basic understanding of BenSower's write up, you're referencing the wrong connection pool when you create your 'Song' schema, and thus, referencing the wrong pool when saving. I guess this results in a time out, have not looked further, but I'm sure a more in-depth answer exists somewhere.
import mongoose from 'mongoose';
const Song = mongoose.model('Song', SongsInfo);
As BenSower states in their answer "For me, the big disadvantage of creating multiple connections in the same module, is the fact that you can not directly access your models through mongoose.model, if they were defined "in" different connections". They're spot on with this one. Having finally overcome this obstacle, I shall have a look into createConnection on another project. For now, good ol' connect() will fix this issue, and do just fine :D