skip to Main Content

I have to receive message from the visitor on the website

const mongoose = require("mongoose");
mongoose.connect("mongodb+srv://hello:[email protected]/")
  .then(() => {
    console.log("mongodb connected");
  })
  .catch(() => {
    console.log("failed to connect");
  });

const LoginSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  message: {
    type: String,
    required: true
  }
});

const collection = mongoose.model("Collection2", LoginSchema);

module.exports = collection; // Export the collection model

I have tried commenting the required or setting it to false and adding the bodyParser. But I want these fields on my mongodb online. After exporting this collection to my main js file I do the following

// Send Message receive details
app.post("/",async (req,res)=>{
    const data={
        name :req.body.name,
        email:req.body.email,
        message:req.body.message
    }
    await collection.insertMany([data]);
    const responseHTML=`<script> alert("${"Your msg is sent"}"); </script>` ;
    res.sendFile("C:\Users\acool\Desktop\myPortfolio-master\index.html");
    res.send(responseHTML);
    
})

I am very new to this. Any help would be deeply appreciated

I have tried adding bodyParser.
I have removed the required:true but then it these fileds arent saved on the database
I have tried saving the document but I want it to be user entered on the website.

2

Answers


  1. required: true in mongoose means that that filed will always be provided. if you remove require: true, you can add default: "" for it to show in your database. Always remember that if you are not using findAndUpdate() in mongoose then you have to save() before any response. in your case

    const myCollection = await collection.insertMany([data]);
    await myCollection.save();
    
    Login or Signup to reply.
  2. Firstly, ensure you are using the body-parser in your app.js/server.js/index.js or wherever your main file is like so:

    app.use(express.urlencoded({ extended: true} ));
    app.use(express.json());
    

    Secondly, Mongoose has a specific method for creating a new document. The Model.create is preferred for inserting one document. The insertMany is perfectly valid but semantically it doesn’t make sense to use insertMany just to insert one document. In your case it looks like create would be more appropriate. Here is a sample of it’s use within a try/catch block for better error handling:

    app.post('/', async (req, res) =>{
       console.log(req.body); //< Make sure data is parsed and present in req.body
       try{
          const {name, email, message} = req.body;
          const newMessage = await collection.create({name, email, message});
          res.status(200).json({
             newMessage : newMessage
          });
       }catch(err){
          console.log(err); //< Check what went wrong on server
          res.status(400).json({
             error : 'Appropriate error message sent to front-end'
          });
       }
    });
    

    An alternative to Model.create() would be construct the document first using a new instance of the Model and then calling save() on that new instance like so:

    app.post('/', async (req, res) =>{
       console.log(req.body); //< Make sure data is parsed and present in req.body
       try{
          const {name, email, message} = req.body;
          const newMessage = new collection({ name, email, message });
          await newMessage.save();
          res.status(200).json({
             newMessage : newMessage
          });
       }catch(err){
          console.log(err); //< Check what went wrong on server
          res.status(400).json({
             error : 'Appropriate error message sent to front-end'
          });
       }
    });
    

    You can read more here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search