简体   繁体   中英

How to create dynamic database in mongodb?

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:avnish@cluster0.ojaf1.mongodb.net/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.

While I don't agree that each type of document should get an entire database I will explain how to handle this case.

mongoose handles connections at the db level, While Mongodb allows a single connection to have multiple databases this is not the case here.

This means you'll have to create another mongoose instance and connect to the other database. This also means you can just do require('mongoose') anymore for the none default connection as this would be a different mongoose instance. I recommend creating a singleton that will serve the connection on demand to deal with this.

I will also add that mongoose is VERY inconvenient for this use case, I recommend you reconsider the actual need for another database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM