skip to Main Content

I am building a MERN app where I want to use a POST method to send data to my collection in MONGODB.
I imported schema as Messages

here is the code

app.post("/messages/new",(req,res) => {
    const dbMessage = req.body;
    
    Messages.create(dbMessage,(err,data) => [
        if(err){
            res.status(500).send(err);
        }
        else{
            res.status(201).send(data);
        }
    });
});

The above way is depreciated which I found later.
What is the latest way to handle this?

2

Answers


  1. Chosen as BEST ANSWER

    I found an answer

    app.post("/message/new", (req, res) => {
      const message = req.body.message;
      const newMessage = new Message({
        "message": message,
      });
      newMessage.save();
      res.status(200).json(newMessage);
    });
    

  2. You made typo on line 2:

    const dbMessage = req.body;
    

    Another typo on line 3:

    Messages.create(dbMessage,(err,data) => {
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search