1

I have a form. I need to get text from my form to save it in MongoDB.

tweets.ejs:

<form method="post" action="/tweets">
<input type="text" id="txt" name="text"/>
<input type="button" id="btn" value="Touch me">
</form>

Here is my route file tweets.js:

var Message = require('models/messages');
exports.get = function(req,res) {
    res.render('tweets')
};

I use mongoose schema(models/messages.js):

var mongoose = require('../libs/mongoose'),
    Schema = mongoose.Schema;
var MessageSchema = new Schema({
    message: String,
    date: Date
});
var Message = mongoose.model('Message', MessageSchema);
module.exports = Message;

I tried set var m = req.body.text in tweets.js, but I think it's absolutely wrong way

exports.post = function(req,res){
    var m = new Message;
    m.message = req.body.text;
    m.save(); }

Explain me how to do it right please!

1
  • did you create /tweets POST route? Commented Nov 15, 2014 at 9:40

1 Answer 1

1

in your routes or app file route should be

var tweets = require("tweets");
app.post("/tweets", tweets.post);

in your tweets.js file

var Message = require('models/messages');
exports.post = function(req,res){
console.log(req.body.text)
var msg = {message:req.body.text,date:new Date()};

Message(msg).save(function(error,data){
if (data){
console.log("Save "+ JSON.stringify(data));
res.send({statud:"OK",msg:data})
}
else{
res.send({statud:"Cancel"})
}
});
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes! Thank you! I didn't use post in route(I just forgot o_O). Now it saves data, but when I push submit button page can not reload and just freezes. I changed type=button to type=submit
response was not set, now edit and add res.send().. every REQUEST have RESPONSE ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.