I'm learning MERN stack development, when I tried to connect the database through .env file, everything was working fine. Here is how my database string looks like:
MYDATABASE_String="mongodb+srv://avnish:[email protected]/registeredUsers?retryWrites=true&w=majority"
It is working fine when I'm trying to register users, they go under registeredUsers. But now, I'm also implementing blog portion, so when I publish a new blog, it goes under registeredUsers.
Now I want to know how to create a new database dynamically so that it goes to blogContent database and not in registeredUsers database.
Here is how my server.js looks like:
const express = require('express');
const mongoose = require('mongoose')
const app = express();
const dotenv = require('dotenv')
const routesURLs = require('./routes/routes')
const registerRouter = require('./routes/register')
const loginRouter = require('./routes/login')
const blogRouter = require('./routes/blog')
const cors = require('cors')
dotenv.config()
mongoose.connect(process.env.DATABASE_ACCESS,{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex:true
},()=>console.log(
'database connected successfully'),
)
app.use(express.json())
app.use(cors())
app.use('/',routesURLs)
app.use('/register',registerRouter)
app.use('/publish',blogRouter)
app.listen(4000, () => {
console.log(`Server started on port`);
});
This is my blog schema:
const mongoose = require('mongoose')
const blogModel = new mongoose.Schema({
title:{
type:String,
required:true,
},
category:{
type:String,
required:true,
},
slug:{
type:String,
required:true,
},
description:{
type:String,
},
content:{
type:String,
required:true
},
featuredImage:{
type:String,
},
publishedAt:{
type:Date,
default:Date.now
}
})
module.exports = mongoose.model('blog',blogModel)
And this is my blog.js
const { response, request } = require('express');
const express = require('express');
const router = require('express').Router();
const blogModel = require('../models/Blog')
router.post('/',async (req,res)=>{
const blogArticle = new blogModel({
title:req.body.title,
description:req.body.description,
category:"haha",
slug:"some-thing-here",
content:req.body.description,
})
blogArticle.save().then(data=>{
res.json({
data:data,
message:"Hurray all done"
})
}).catch(error=>{
res.json({
error:error,
message:"Lol! Nothing works"
})
})
})
module.exports = router;
Note When I removed registeresUsers from the mydatabase string, every data goes to Test database.