L
L
Little Vasya2019-03-31 17:35:38
Node.js
Little Vasya, 2019-03-31 17:35:38

Project file structure?

Recently, I started studying Node, the ExpressJS framework... I wondered about the structure of the project files, I made such an assembly, I need your opinions .. or are there ready-made solutions?

backend
. . . controllers
. . . . . . posts.controller.js
. . . models
. . . . . . posts.models.js
. . . db.js
. . . router.js
. . . server.js

posts.models.js
const mongoose = require('mongoose');

const postsSchema = mongoose.Schema({
    title: String,
    description: String,
    date: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('posts', postsSchema);

posts.controller.js
const Posts = require('../models/posts.models');

exports.module = {
    async post (req, res) {
        const post = new Posts({
            title: req.body.title,
            description: req.body.description
        });

        await post.save();

        res.json({
            message: 'created',
            data: post
        })
    },

    async all (req, res) {
        const posts = await Posts.find()
        res.json({
            data: posts
        })
    }
};

router.js
const load = (controller) => require(`./controllers/${controller}.js`);

module.exports = function (app) {
    app.get('/', load('posts.controller').module.all);
    app.post('/posts', load('posts.controller').module.post);
};

server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const db = require('./db');

const app = express();

app.use(cors());
app.use(bodyParser.json());

require('./router')(app);


db.connect('mongodb://localhost:27017/blog', (err) => {
    if (err) return console.log(err);
    app.listen('3000', () => console.log('Server started'))
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question