Once I have filled out input
, I would like to send it in JSON via AJAX to server. However, upon sending the data, the server says ValidationError: Post validation failed: text: Path 'text' is required.
. When I console.log(req.body.post)
on the server, it says undefined
. I try to find out what's wrong but still not able to resolve it.
HTML
<form action="/main/messages" id="homePagePostForm">
<input type="text" class="form-control" id="homePagePostInput" name="post[text]">
<input type="button" id="homePagePostInputButton" style="display:none">
</form>
AJAX
$.ajax({
url: "/main/home",
type: "POST",
contentType: "application/json",
data: JSON.stringify({
post:{"text": $("#homePagePostInput").val()}
});
})
NodeJS/Mongoose
router.post("/main/home", function(req, res){
User.findById(req.user._id, function(err, currentUser){
if(err){
console.log(err);
} else {
//it says undefined for req.body.post
console.log(req.body.post)
Post.create(req.body.post, function(err, post){
if(err){
console.log(err);
//request made it ways here, and ends here.
res.redirect("/main/home");
} else {
......
Post's Schema
var postSchema = mongoose.Schema({
text: {type: String, required: true},
date: Date,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
likes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
],
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});