简体   繁体   中英

How to save Data in MongoDB from forms

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!

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"})
}
});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM