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
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 caseFirstly, ensure you are using the body-parser in your app.js/server.js/index.js or wherever your main file is like so:
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 useinsertMany
just to insert one document. In your case it looks likecreate
would be more appropriate. Here is a sample of it’s use within atry/catch
block for better error handling:An alternative to
Model.create()
would be construct the document first using a new instance of the Model and then callingsave()
on that new instance like so:You can read more here.