skip to Main Content
//mongoose Schema for how the data structure from front end should be 

import mongoose from 'mongoose';

const postSchema = mongoose.Schema({
    title: String,
    message: String,
    creator: String,
    tags: [String],
    selectedFile: String,
    likeCount: {
        type: Number,
        default: 0
    },
    createdAt: {
        type: Date,
        default: new Date()
    },
});

const PostMessage = mongoose.model('PostMessage', postSchema);

export default PostMessage;
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors'

import postRoutes from './routes/posts.js';

const app = express();

app.use(cors());

app.use('/posts', postRoutes) //every routes in postRoutes is only reached by posts

app.use(bodyParser.json({ limit:"30mb", extended: true}));
app.use(bodyParser.urlencoded({ limit:"30mb", extended: true}));

const CONNECTION_URL = 'mongodb+srv://<hidden on purpose>@cluster0.ynprayr.mongodb.net/?retryWrites=true&w=majority';
const PORT = process.env.PORT || 5000;

mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology:true })
    .then(() => {app.listen(PORT, ()=> console.log(`Server running on port: ${PORT}`))})
    .catch((error) => console.log(error.message));
logic for creating a post which the mongoose checks before saving to the database

import PostMessage from '../models/postMessage.js';

export const getPosts = async(req, res) => {
    try{
        const postMessages = await PostMessage.find();

        res.status(200).json(postMessages);
    }
    catch(error){
        res.status(404).json({ message: error.message });
    }
};

export const createPost = async (req, res) => {
    const post = req.body;

    const newPost = new PostMessage(post)
    try{
        await newPost.save();

        res.status(201).json(newPost);
    }
    catch(error) {
        res.status(409).json({ message: error.message });
    }
}

basically postman only shows the data of the tags:[] createdAt and likeCount while the other part of the schema isnt showing even after creating a form for the server side, the network tab in my browser console acknowledge the payload data from the front end but the review shows only the (tags as an square bracket, createdAt, likecount and id etc..)

2

Answers


  1. I think you should save the data first and then send it as a JSON
    For example:

    const updatedPost = await newPost.save();
    
    res.status(201).json(updatedPost);
    
    Login or Signup to reply.
  2. You’re using an incorrect order for configuring Express:

    app.use('/posts', postRoutes);
    app.use(bodyParser.json({ limit:"30mb", extended: true}));
    app.use(bodyParser.urlencoded({ limit:"30mb", extended: true}));
    

    Because you’re declaring the body-parser middleware after your /posts routes, any requests for those routes will never be passed through the body-parser middleware.

    You should declare the routes after body-parser so any requests will first be properly parsed before being passed to your route handlers:

    app.use(bodyParser.json({ limit:"30mb", extended: true}));
    app.use(bodyParser.urlencoded({ limit:"30mb", extended: true}));
    
    app.use('/posts', postRoutes);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search