高级节点中的数据库连接错误和快速FCC挑战-护照用户的序列化

Database connection error in advanced node and express FCC Challenge-Serialization of a passport user

这是 freecodecamp 挑战 link 请帮我解决这个问题 FCC challenge link

我在 FCC 挑战中遇到数据库连接错误,谁能帮帮我。 This the image showing errors

我的小故障项目Link https://glitch.com/~chivalrous-pharaoh-mqknswso2j

Server.js代码

‘use strict’;

const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const fccTesting = require(’./freeCodeCamp/fcctesting.js’);
const session = require(‘express-session’);
const passport = require(‘passport’);
const ObjectId = require(‘mongodb’).ObjectId;
const mongodb = require(‘mongodb’).MongoClient;
const app = express();

fccTesting(app); //For FCC testing purposes
app.use(’/public’, express.static(process.cwd() + ‘/public’));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set(‘view engine’, ‘pug’)

app.get(’/’, function (req, res) {
res.render(’/app/views/pug/index.pug’, {title: ‘Hello’, message: ‘Please login’})
})

mongodb.connect(process.env.DATABASE, (err, db) => {
if(err) {
console.log('Database error: ’ + err);
} else {
console.log(‘Successful database connection’);
//serialization and app.listen

}});

app.use(session({
secret: process.env.PORT,
resave: true,
saveUnintialized: true
}));

passport.serializeUser((user, done) => {
done(null, user._id)
})

passport.deserializeUser((id, done) => {
mongodb.collection(‘users’).findOne(
{_id: new ObjectId(id)},
(err, doc) => {
if(err){
return done(err);
}
return done(null, doc);
}
);
});

app.use(passport.initialize);
app.use(passport.session);

app.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT);
});

.env

SECRET=
MADE_WITH=
SESSION_SECRET=
DATABASE= 'mongodb+srv://Kuljeet:********@cluster0-gxlnb.mongodb.net/test?retryWrites=true&w=majority'

我想你必须在 server.js 中加载你的环境变量,这样你才能阅读 process.env.DATABASE。

您可以使用 dotenv 库。 https://www.npmjs.com/package/dotenv

  1. npm install dotenv在你的项目中
  2. require('dotenv').config() 添加到您的 server.js

例如

‘use strict’;

require('dotenv').config();
const express = require(‘express’);

希望这能回答您的问题。