model -> register function
validation is done now
Create new db in atlas
db name - ComplexApp collection name - users
In the root create new file - db.js
npm install mongodb
Require the file
const mongodb = require('mongodb')
const connectionString = 'conn string'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
module.exports = client.db()
})
Make db startup file
Open app.js
Go to end
delete app.listen line
module.exports = app
Go to db
const app = require('./app')
app.listen(3000)
package.json
change in watch app to db
test
Correct this function
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: false}, function(err, client){
module.exports = client.db()
const app = require('./app')
app.listen(3000)
})
The app in this structure will not begin till we've had a chance to export the mongodb database.
Now we can work with the database in any file where we just require the db.js file.
Now we will use db in model file
in model const usersCollection = require('../db').collection("users")
Now we can perform crud on this usersCollection variable.
in register
check for validation errors
if(!this.errors.length){
usersCollection.insertOne(this.data)
}
test this out
fill in the form - value should be in db
db.js
new file - .env
setup connectionstring and port
in db.js
npm install dotenv
Top line
const dotenv = require('dotenv')
dotenv.config()
in the mongodb.connect() function
replace first argument with
process.env.CONNECTIONSTRING
test app
Do same thing for port
go to .env
PORT=3000
in db.js
app.listen(process.env.port)