How to save Data in MongoDB from forms - javascript

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

Related

Print array in node js server

Hi I have a website from witch I can send a message to node js server and there the message is saved in a a array. When a new message is sent to the server the old message in the array is overwritten by the new message. The array has to contain new and old messages.
The output of console after sending message
const http = require('http');
const { Socket } = require('socket.io');
const WebSocketServer = require('websocket').server;
var steviloSporocil = 0;
const sporocila=[];
const server = http.createServer();
console.log('Server is on port 3000')
server.listen(3000);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
connection.on('message', function(message) {
sporocila[steviloSporocil]=[message.utf8Data];
steviloSporocil++;
for (let i = 0; i < steviloSporocil; i++) {
connection.sendUTF(sporocila[i]);
console.log('Received Message:', sporocila[i]);
}
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.');
});
});
<?php ob_start() ?>
<?php $titel="Chat"; ?>
<div class="chat-main" id="text"></div>
<form name='form' method='post' class="form">
<div class="form-group">
<input type="text" class="form-control" id="textbox" name="chat" placeholder="Chat">
<button type="button" class="btn btn-primary" name="gumb" id="gumb" onclick="Poslji()" autocomplete="off">Send</button>
</div>
</form>
<script>
function Poslji(){
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = function() {
console.log('WebSocket Client Connected');
ws.send(document.getElementById('textbox').value);
};
ws.onmessage = function(e) {
console.log("Received: '" + e.data + "'");
document.getElementById('text').innerHTML=e.data;
};
}
</script>
<?php
$content=ob_get_clean();
require "layout.html.php";
?>
If I understood everything, here how to solve your problem:
you take all previous message at the specified index and add the new one at the end. If you want to add it at the top, then just invert the two lines.
sporocila[steviloSporocil] = [
...sporocila[steviloSporocil],
message.utf8Data
];
You are sending the messages in the array to the client separately using a for-loop and connection.sendUTF(sporocila[i]); and then displaying the last message received using document.getElementById('text').innerHTML=e.data;.
Are you suprised then that your website only shows the last item in the array?
Why not send the entire array using JSON.stringify and then JSON.parse on the client?

Node js not sendin messages to clients

Hi I am making a simple chat website with node js. I want everyone to see posted messages. The messages are stored in a array and then displayed on the website. The problem is that when a message is posted no one can see it. A user will be able to see it after posting a new message. Can someone help?
const http = require('http');
const { Socket } = require('socket.io');
const WebSocketServer = require('websocket').server;
var steviloSporocil = 0;
let sporocila=[];
const server = http.createServer();
console.log('Server is on port 3000')
server.listen(3000);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
connection.on('message', function(message){
sporocila.push(message.utf8Data);
connection.sendUTF(JSON.stringify(sporocila));
console.log('Received Message:', JSON.stringify(sporocila));
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.');
});
});
<?php ob_start() ?>
<?php
$titel="Chat";
$nekaj=$_SESSION['uporabnik'];
?>
<div class="chat-main" id="text"></div>
<form name='form' method='post' class="form">
<div class="form-group">
<input type="text" class="form-control" id="textbox" name="chat" placeholder="Chat">
<button type="button" class="btn btn-primary" name="gumb" id="gumb" onclick="Poslji()" autocomplete="off">Send</button>
</div>
</form>
<script>
var myInput = document.getElementById("textbox");
var up='<?php echo $nekaj; ?>';
function Poslji(){
if(myInput && myInput.value){
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = function(){
ws.send(up+": "+document.getElementById('textbox').value+"<br>");
};
ws.onmessage = function(e) {
const arr=JSON.parse(e.data);
console.log("Received: '"+e.data+"'");
document.getElementById('text').innerHTML=arr;
};
}
}
</script>
<?php
$content=ob_get_clean();
require "layout.html.php";
?>

How can I get a req.body from a form that is not undefined?

Whenever I submit a form with information it is returned as undefined. I have posted the code below. If I include the (enctype="multipart/form-data") in my form I dont receive anything for the body (req.body). However, if I dont include it I receive a body but the file processing does not work and the page just keeps loading.
app.post('/processupload', function(req, res) {
var date = new Date();
titles.push(req.body.pTitle);
descriptions.push(req.body.postDescription);
dates.push(date.toString());
file_names.push(req.body.fUpload);
console.log(req);
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files)
{
if(err) return res.redirect(303, '/error');
});
form.on('end', function(fields, files)
{
var temp_path = this.openedFiles[0].path;
var file_name = this.openedFiles[0].name;
var new_location = __dirname + '/public/images/';
fs.copy(temp_path, new_location + file_name);
res.redirect(303, 'home');
});
});
<form action="/processupload" enctype="multipart/form-data" method="POST" id="uploadForm" name="postForm">
<p align="center" id="pUploadForm" name="pPostForm"><label for="photoTitle">Photo Title: </label>
<input type="text" id="photoTitle" name="pTitle"><br>
<br><input type="file" id="fileUpload" name="fUpload"><br>
<br><label for="photoCaption">Photo Caption: </label><br>
<textarea rows="10" cols="50" id="photoCaption" name="postDescription"></textarea><br><br>
</p>
</form>
I created a project few weeks back that had photo upload. I used Angular and Node. But it should still work without Angular only using Node. I used multer npm package.
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var multer = require('multer');
var upload = multer({ storage: multer.memoryStorage() }); //Save photo in memory
router.post('/processupload', upload.single('photo'), function(req, res, next){
var bucketName = process.env.BUCKET_NAME;
var file = req.file;
var filename = file.originalname;
var ext = _.last(filename.split('.'))
var keyName = uuid.v4() + '.' + ext;
var url = process.env.AWS_URL + bucketName + '/' + keyName;
var params = { Bucket: bucketName, Key: keyName, Body: file.buffer, ACL: 'public-read' };
s3.putObject(params, function(err, data) {
if (err){
return res.status(400).send(err)
} else{
console.log("Successfully uploaded data to myBucket/myKey");
console.log("The URL is", url);
res.send(url)
}
});
});
This helped me uploading images then gives me back the image url from the S3 Bucket. But you can handle that file as you want. Multer allows you to access to req.file so you can do whatever you need to do, in this example I created a unique id in order to get a url to send back to the front-end and therefore use it a source somehow. This is a form working with this code:
<form action="/testupload" method='post' enctype='multipart/form-data'>
<input type="file" name="photo" id="photo" multiple=false>
<button type="submit">Submit</button>
</form>
Something important that took a long time to debug though the name="photo" in the form must be reflected by the upload.single('photo') middleware. I hope this helps, there are so many ways go around this, this is just one.
Sources:
https://www.npmjs.com/package/multer
http://docs.aws.amazon.com/AmazonS3/latest/UG/UploadingObjectsintoAmazonS3.html

Upload images to uploads folder _ JavaScript

Users will be able to either send a text post(input type="text") or image post(input type="file"). But they won't be sending both
Here's my form (in Jade):
form#addPost(action="/uploads", method="post", placeholder='Add your ideas here...')
input#postinput(type="text", name="contents" placeholder="Add your ideas here...")
div.privacy(class="onoffswitch", id='privacytog')
input(type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked)
label(class="onoffswitch-label" for="myonoffswitch")
span(class="onoffswitch-inner")
span(class="onoffswitch-switch")
<div style="height:0px;overflow:hidden">
<input type="file" id="fileInput" name="fileInput" accept="image/*">
</div>
input#submit1(type="submit", value="Post")
And Here's my app.js(server-side code)
var util = require("util");
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require("multer");
app.use(multer({
dest: "./public/uploads/"
}));
app.post("/uploads", function(req, res) {
var data = req.body;
var id = req.user._id;
var username = req.user.username;
var date = Date();
var onOff = false;
if (req.body.onoffswitch) {
onOff = true;
}
//Images upload to uploads folder
if (req.files) {
console.log(util.inspect(req.files));
if (req.files.fileInput.size === 0) {
return next(new Error("Hey, first would you select a file?"));
}
fs.exists(req.files.fileInput.path, function(exists) {
if(exists) {
res.end("Got your file!");
} else {
res.end("Well, there is no magic for those who don’t believe in it!");
}
});
}
User.findById(id, function(err, user) {
if (err) return handleErr(err);
var uid = shortid.generate();
newPost = {
//If sending down an Image use data.fileInput not contents
contents: [data.contents || '/img/'+data.fileInput],
_id: uid,
privacy: onOff,
username: req.user.username,
date: date,
rating: Number(0),
uwv: []
};
user.posts.push(newPost);
user.save(function(err, user){
if(err) return handleErr(err);
if(newPost.privacy === 'false'){
for (var i = 0; i < user.followers.length; i++) {
User.findOne({username:user.followers[i]}, function(err, follower){
follower.discover.push(newPost)
follower.save();
});
}
}
});
});
}
Images are being uploaded and saved to uploads folder. However when posting just a text post(only filling in input type="text") it keeps throwing back the error: Cannot read property 'size' of undefined
Typically browsers will not send the file field if there is no file selected, so there is no way for the backend to know that there was such a field.
Instead just check for the existence of the file field: if (!req.files.fileInput). You may also want to check that the file is not empty: if (!req.files.fileInput || !req.files.fileInput.size)

Express auth app not hangs on form submit

I am trying an Example from Jump start node.js(chapterote 1 Authentication).I wrote all the program and created all the files and folders witch is needed for chapter 1.For those who dont know Chapter 1 is about using mongolab cloud Service.
form.html
<form action="/signup" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div><input type="submit" value="Sign Up"/></div>
</form>`
lib/db.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports.mongoose = mongoose;
module.exports.Schema = Schema;
// Connect to cloud database
var username = "user"
var password = "password";
var address = ' #dbh42.mongolab.com:27427/nockmarket';
connect();
// Connect to mongo
function connect() {
var url = 'mongodb://' + username + ':' + password + address;
console.log('[*] not reaching here');
mongoose.connect(url);
}
function disconnect() {mongoose.disconnect()}
models/User.js
var db = require('../lib/db');
var UserSchema = new db.Schema({
username : {type: String, unique: true}
, password : String
})
var MyUser = db.mongoose.model('User', UserSchema);
// Exports
module.exports.addUser = addUser;
// Add user to database
function addUser(username, password, callback) {
var instance = new MyUser();
instance.username = username;
instance.password = password;
instance.save(function (err) {
if (err) {
callback(err);
}
else {
callback(null, instance);
}
});
}
When I sumbits the form app hangs and its not calling connect() function witch connects to the mongolab it just waits for finish but nothing happens.
thanks,

Categories