skip to Main Content

I am a beginner and starting to learn MongoDB, NodeJS and Express by creating a simple blog project. I facing a problem as my data cannot be stored in my MongoDB event though my MongoDB connects properly. There may be a mistake in my coding in index.js. I try to fix it, but it does not store the information that I submit in the blog. Please help me. Thank you.

This is my code in index.js. You can see my full file in this link if you want to test it. enter link description here

This is my index.js

const express = require('express')
const path = require('path')
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/my_database',{useNewUrlParser: true})

const app = new express()
const ejs = require('ejs')

const BlogPost = require('./models/BlogPost')

app.set('view engine', 'ejs')

app.use(express.static('public'))

const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))

const { error } = require('console')

app.listen(4000, () => {
    console.log('App listening on port 4000')
});

app.get('/',(req,res)=>{
    res.render('index')
})

app.get('/about', (req, res) => {
    res.render('about');
});

app.get('/contact', (req, res) => {
    res.render('contact');
});

app.get('/post',(req,res)=>{
    res.render('post')
 })

 app.get('/posts/new',(req,res)=>{
    res.render('create')
})

app.post('/posts/store',(req,res)=>{
    BlogPost.create(req.body,(error,blogpost)=>{
        res.redirect('/');
    });
});

This what it show in my MongoDB compass

enter image description here

2

Answers


  1. I think the database connection URL is not correct .

    You can use following code,

    const mongoose = require('mongoose'); 
    
    mongoose.connect(db_url,{ useNewUrlParser: true }, function (err) { 
    if (err) throw err; console.log('Successfully connected'); });
    
    Login or Signup to reply.
  2. app.post('/posts/store',async (req,res)=>{
        let blog = await BlogPost.create(req.body);
        res.render('index',blog);
    });
    

    you can access the blog data inside the index file by blog variable

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search