Home > Net >  MongoDb is connected but cannot store title and body
MongoDb is connected but cannot store title and body

Time:10-26

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('/');
    });
});

CodePudding user response:

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'); });

CodePudding user response:

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

  • Related