0

The idea of the program is to send messages. User enter to the web select his id as (Sender) and select a (Receiver) id then press Submit. After that it takes him to a page shows all the messages were send to him with a box for him to send a message to the person that he chose his id (Receiver) previously.

I have an error and I don't know where . The program is not finished yet but I need to fix the error before moving.

messages.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const messageSchema = new Schema({

    message : {
        type : String,
    },

    sender : {
        type : Number,
    },
    receiver : {
        type : Number,
    },

});

const Message = mongoose.model('Message', messageSchema);
module.exports = Message;

message.js //repository

const Message = require('../models/messages');
const mongoose = require('mongoose');
class MessageRepository {


    async getMessages() {
            return await Message.find();
    }
    async addMessage(message) {
        message = await Message.create(message);
        return message;
    }

}
module.exports = new MessageRepository();

message.js //services

const messageRepo = require('../repo/message')
class MessageService {


    async addMessage(req, res) {
        try {
            const messages = req.body;

            await messages.forEach(async(message)=> await messageRepo.addMessage(message))
            res.send('All messages were added')


        } catch (err) {
            res. send(err)
        }
    }
    async getMessages(req, res) {

        try {
            const message = req.query.message;
            const messages = await messageRepo.getMessages(message);
            res.json(messages);
        } catch (err) {
            res.status(500).send(err);
        }

    }


}
module.exports = new MessageService();

app.js

const express = require('express');
const routes = require('./router');
const logger = require('morgan');
const path = require('path');
const mongoose = require('mongoose')

mongoose.connect('mongodb://127.0.0.1:27017/MessageDB',{useNewUrlParser: true , useCreateIndex: true})
    .then(db=> console.log('Database connection was successful'))
    .catch(e=> console.log('Could not connect to database' , e))

const app = express();

const port = 2000;

// app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));

app.use(logger('dev'));
app.use(express.json());

app.use('/api', routes);
app.listen(port, ()=>{
    console.log(`Server started @ http://localhost:${port}`);
})

router.js

const express = require('express')
const messageService = require('./services/message')

const router = express.Router();


router.post('/messages/addMessages', messageService.addMessage());



router.get('/messages',messageService.getMessages())
    .post('/messages/addMessages', messageService.addMessage());




module.exports = router;

1 Answers1

0

First of all, it would be good to know what error you are having there so that everyone has better understanding of what is going on and can help you out.

After I looked at your code, I can point out somethings might cause issues.

In router.js, Express.js router functions expect second parameter as callback function or a reference of callback function but you pass a function invocation.

So it should be something like this.

router.post('/messages/addMessages', messageService.addMessage);

router.get('/messages',messageService.getMessages)
    .post('/messages/addMessages', messageService.addMessage);

and another thing I can tell is forEach() is not good pair with async/await. (use for...of instead) There are many questions/answers about this matter. so if you would like to know more about it then you can have a look at them. Stack overflow: Using async/await with a forEach loop

Jake Noh
  • 216
  • 1
  • 7