Mongoose giving me undefined error - node.js

OK i don't get this one bit. it was actually working just fine a while ago but now i'm getting the following error:
ERROR
azura#AzuraMain:~$ nodejs /home/azura/Desktop/dbWrite.js
Connection to database has been established
Server is up
/home/azura/Desktop/dbWrite.js:94
res.send("<h1>Hello</h1> " + id + " " + data.name);
^
TypeError: Cannot read property 'name' of undefined
at /home/azura/Desktop/dbWrite.js:94:53
at /home/azura/node_modules/mongoose/node_modules/kareem/index.js:160:11
at Query._findOne (/home/azura/node_modules/mongoose/lib/query.js:1145:12)
at /home/azura/node_modules/mongoose/node_modules/kareem/index.js:156:8
at /home/azura/node_modules/mongoose/node_modules/kareem/index.js:18:7
at process._tickCallback (node.js:415:13)
I dont understand why i would be getting this error.
Here's my code:
SERVER CODE
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
//Use These Modules
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
//Create the homepage of the server
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
console.log("Connection to database has been established");
//Connect to the database
var collectedData = new mongoose.Schema({
ipAddress: String,
name: {
type: String,
unique: false
}
});
var collectionOfData = mongoose.model("dataType", collectedData);
//Create the mongoose schema
io.on("connection", function (socket) {
//Check for connection with socket.io
socket.on("name", function (e) {
//Check for "name" with socket.io
var ip = socket.request.socket.remoteAddress;
//Check the ip address of user
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
name: e
});
//Create the Schema with the requested name and ip
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
//Save this into the database
});
});
app.get("/mix", function (req, res) {
collectionOfData.find(function (err, data) {
res.send(data);
});
});
//Just a test directory /mix
app.get("/:uniqueURL", function (req, res) {
var id = req.params.uniqueURL;
//Create a unique URL
collectionOfData.findOne({
_id: id
}, function (err, data) {
res.send("<h1>Hello</h1> " + id + " " + data.name);
//This is where the issue derives from data.name is undefined? I Defined it up there and it seems to work for a second until the server crashed because of it
});
//Send the data to the requested page
});
http.listen(10203, function () {
console.log("Server is up");
});
//Create the HTTP Server
HTML CODE
<html>
<body>
<form id="chooseName">
<input class="center-block" id="name" placeholder="Post whatever the fuck you want" />
</form>
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"> </script>
<script>
var socket = io();
$("#chooseName").submit(function (e) {
e.preventDefault();
socket.emit("name", $("#name").val());
document.write("cool go to http://173.78.185.247:10203/mix to see what you have contributed to");
});
//Send data to the server where it gets read with socket.on("name", Do Something
</script>
</body>
</html>
why does this happen? all i want is to make data.name print out the requested name of the user. it seems to work for a second but then the server just crashes.

if there is no matching document in collection data then findOne() can provide null in data object.
debug by printing id, err, and data.

Related

Socket.io - server receives message but doesn't emit it to clients using nodejs and mongodb?

when i run the code, the server server side receive the message but the client side doesnt get anything until they send message. however in html doesnt show anything wrong
i have this server code:
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors')
const { socket } = require('socket.io');
io.on('connection', () =>{
console.log('a user is connected')
})
i have this route:
var http = require('http').Server(router);
var io = require('socket.io')(http);
// Render Message
router.get('/messages/:id', async function (req, res, next) {
user = await User.findOne({_id: req.session.userId}, {username: 1})
return res.render("user/messages.ejs", {user: user, booking: req.params.id});
});
// Display Message from DB
router.get('/messageslist/:booking', (req, res) => {
Message.find({booking: req.params.booking})
.populate({
path: "pro",
model: Pro,
}).populate({
path: "user",
model: User,
}).exec().then((data) => {
res.json(data)
})
})
router.post('/messages', async (req, res) => {
const {booking, user, message} = req.body;
try {
var msg = new Message({
booking: booking,
message: message,
user: user
});
var savedMessage = await msg.save()
console.log('saved');
io.emit('message', req.body);
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
return console.log('error', error);
} finally {
console.log('Message Posted')
}
})
this is my html:
var socket = io();
$(() => {
$("#send").click(() => {
sendMessage({
booking: $("input[name=booking]").val(),
user: $("input[name=user]").val(),
message: $("#message").val()
});
})
getMessages()
})
socket.on('message', addMessages)
function addMessages(message) {
if (message.user && message.user != '') {
if ($("input[name=user]").val() == message.user._id) {
html = '<div class="msg right-msg"><div class="msg-img" style="background-image: url(' + message.user.image +
')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.user.username +
'</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
} else {
html = '<div class="msg left-msg"><div class="msg-img" style="background-image: url(' + message.pro.image +
')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.pro.username +
'</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
html += '<div class="msg-text">' + message.message + '</div></div></div>'
window.scrollTo(0, document.body.scrollHeight);
$("#msger-chat")+$(".msger-chat").append(html)
}
function getMessages() {
$.get('http://127.0.0.1:3000/messageslist/<%=booking%>', (data) => {
data.forEach(addMessages);
})
}
function sendMessage(message) {
$.post('http://127.0.0.1:3000/messages', message)
}
When i run it, my server outputs: User connected and message saved;. But my client doesn't get a response
I think the problem is you are creating two io instances. One in server code
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors')
const { socket } = require('socket.io');
io.on('connection', () =>{
console.log('a user is connected')
})
another one is in route handlers
var http = require('http').Server(router);
var io = require('socket.io')(http);
You should have a singleton io object which is responsible to handle all the activities. This is an approach how to create such design. you will have mainSocketServer
createSocketServer = (server) => {
// this is how you implemented
var io = require('socket.io')(http);
// this is the part to create singleton object
serverStore.setSocketServerInstance(io);
io.on("connection", (socket) => {
// this socket obj will include
about connected user. this socket is actually connected user client
console.log('a user is connected')
socket.on("direct-message", (data) => {
// you create socket events handler in different file
directMessageHandler(socket, data);
}); });};
module.exports = {
createSocketServer,
};
you need another file where you store all the connected users. usually in socket server, users are stored in a Map
const connectedUsers = new Map();
let activeRooms = [];
let io = null;
// we call this in mainSocketServer file
const setSocketServerInstance = (ioInstance) => {
io = ioInstance;
};
// you export this and use it anywhere on your server
const getSocketServerInstance = () => {
return io;
};
On the client side where you listen for sockets, you do not pass reference to the function. 2nd argument is callback function that has received data as parameter and you should call addMessage from inside. Here is the example code:
socket.on('message', (data) => {
addMessages(data)
})
Just update this in front end code and it should work

Using socket.io in modules and routes Express

I am having some issues using socket.io is modules. I have changed the way I do it quite drastically, however everything seems to be working, except being able to send userdata back to my socket connection:
Here is my io.js file: /config/io
/*jshint esversion: 6*/
var io = require('socket.io')();
const moment = require('moment');
// Socket stuff
io.on('connection', function (socket) {
socket.on('login', function (userdata) {
socket.handshake.session.userdata = userdata;
socket.handshake.session.save();
console.log(socket.handshake.session.userdata);
});
// Server Time
var interval = setInterval(function () {
var momentNow = moment();
var data = momentNow.format('LT');
socket.emit('time', data);
}, 60000);
// Chat - Needs work
socket.on('chat', function (msg) {
console.log(msg);
var username = 'Message'; //socket.handshake.session.userdata.username;
var message = '[' + moment().format('LT') + '] ' + username + ': ' + msg;
io.emit('message', message, username);
});
socket.on('disconnect', function () {
if (socket.handshake.session.userdata) {
delete socket.handshake.session.userdata;
socket.handshake.session.save();
}
console.log('user disconnected');
});
});
module.exports = io;
Here is where I'm trying to emit the data /config/passport: (please note that userdata does indeed contain the right information!)
/*jshint esversion: 6 */
const LocalStrategy = require('passport-local').Strategy;
const db = require('../config/db');
const bcrypt = require('bcryptjs');
var io = require('./io');
module.exports = function(passport) {
// Local Strategy login
passport.use(new LocalStrategy(function(username, password, done) {
// Match Username
let sql = 'SELECT * FROM users WHERE username = ?';
db.query(sql, [username], function(err, rows) {
if (err)
return done(err);
if (!rows.length) {
return done(null, false, {
type: 'loginMessage',
message: 'Wrong Login',
});
}
// Match Password
bcrypt.compare(password, rows[0].password, function(err, isMatch) {
if (err)
return done(err);
if (isMatch) {
var userdata = rows[0];
io.emit('login', userdata); // HERE IS WHERE I TRY TO EMIT IT
// console.log(rows[0]);
return done(null, rows[0]);
} else {
return done(null, false, {
type: 'loginMessage',
message: 'Wrong Login',
});
}
});
});
}));
Now here is my main app file: (leaving out a bunch of stuff)
var io = require('./config/io');
// Init App
const app = express();
// Init http server
const server = http.createServer(app);
// Attach IO
io.attach(server);
// Listen
server.listen(8080, function () {
console.log('Server listening on port 8080...');
});
Now, everything seems to be working fine, except being able to emit the data. Now I tried logging it client side as well (just in case it was emitting on client-side and not server-side) but it is not doing that as well.
Okay, so here is an actual working answer. It s a work-around, and I completely abandoned trying to do it from the passport login handler itself. But here is how I did it:
IO code:
var session = socket.handshake.session;
socket.on('login', function () {
if (socket.handshake.session.passport === undefined) {
var destination = '/';
socket.emit('not logged', destination);
} else {
console.log('user logged in');
var userId = session.passport.user;
var sql = 'SELECT * FROM users WHERE id = ?';
var query = db.query(sql, userId, function (err, rows) {
session.userdata = rows[0];
session.save();
var dataObj = session.userdata;
socket.emit('sart up', dataObj);
});
}
});
And jQuery:
// Connection Successful
socket.on('connect', function () {
connected = true;
socket.emit('login');
});
socket.on('disconnect', function () {
connected = false;
});
socket.on('not logged', function (destination) {
window.location.href = destination;
});
socket.on('start up', function (dataObj) {
});
I'm not a huge fan of having to do it this way, I would have liked to handle everything sever-sided, but for now this is working, and will use until I figure out how to do it the way I'd like to.

node/express server. parameter is undefined

What is going wrong with my string parameter?
var express = require('express');
var app = module.exports = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var braintree = require("braintree");
Schema = mongoose.Schema;
var user = require('../shared/userFunctions.js')
//register functions
app.register = function(api) {
api.get('get_client_token', generateClientToken);
api.get('find_customer', findCustomer);
api.post('checkout', checkout);
api.post('create_customer', createCustomer);
api.post('create_payment_method', newPaymentMethod);
}
The checkout function is where I call the local function with user.getuser
function checkout(request, response) {
var email = request.body.email;
var nonce = request.body.payment_method_nonce;
//var nonce = req.param("payment_method_nonce");
var amount = request.body.amount;
// Use payment method nonce here
gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonce,
}, function (err, result) {
if(err){
return response.send(500, "Checkout failed")
}
/* request.add({"amount": 10})
request = nonce;
newPaymentMethod(request);*/
/* return res.send(200, "Checkout Success")*/
});
user.getuser(email, function(u){
console.log("returning user: " + JSON.stringify(u))
return response.send(200, JSON.stringify(u))
})
}
If I hard core the email address into the mongoose query, it returns the user. What gives? Please give advice on my node async style. I am still new to it, but sometimes error first fucntions don't work and sometimes I need "next". The static email works but is my style the problem?
exports.getuser = function(email, res) {
var db = mongoose.connection;
mongoose.connect(process.env.MongoConnectionString);
db.on('error', function () {
});
db.once('open', function callback() {
console.log("Sucessfully Logged into mongo");
User.findOne({email:email}, function (err, user, next) {
if (err) {
mongoose.disconnect();
return next(err);
}
mongoose.disconnect();
console.log("Sending user response");
if(!user){
console.log("failed to get user")
return
}
return res(user);
});
});
EDIT
This function is responsible for calling the internal function. It seems to work exactly like the checkout function, except for its magical ability to work correctly.
function getUser(request, response) {
var email = request.param('email');
user.getuser(email, function(user){
return response.send(200, JSON.stringify(user))
})
};
Using a REST client so I assure you that body/params is not the problem. Thanks for the help thus far.
you can check your paratmeter in your api like this :
var password = req.body.passwordBrow || '';
var uidUser = req.body.uidUser || '';
and then check it :
if(password && uidUser){
// here you can log your parameters
}else{
// the parameter is undefined, so you need to check your request in the client
res.json({
status : "not_ok",
result : "empty_data",
resultType : serverConst.EmptyParams
});
}
hope it helps you.

How to use GridFS to store video(binary data) sent from a device and retrieve binary data using mongodb and node.js [duplicate]

I am trying to figure out how I can post an image directly to GridFS without storing it anywhere on the server as a temporary file first.
I am using Postman (chrome ext.) to post a file, and I manage to store this post as a file using:
req.pipe(fs.createWriteStream('./test.png'));
I am also able to store directly to GridFS from a readStream when the readStream is created from a file on the server. (see code)
I have the following files, saveFromReq.js which listens for the POST and basically just passes this on to the savePic.js.
saveFromReq.js:
var express = require('express');
var app = express();
var savePic = require('./savePic');
var fs = require('fs');
var GridStore = require('mongodb').GridStore;
var pic = './square.png';
var picID;
//When the following
//var pic = fs.createReadStream('./square.png', {autoClose: true});
//is not commented out, and 'req' is replaced with 'pic' in the savePic function,
//the file square.png is stored correctly to GridFS
app.post('/picture', function(req, res){
savePic(req, function(id){});
res.writeHead(200, {'Content-Type': 'text' });
res.end("Sucsess!\n");
});
app.listen(process.env.PORT || 3413);
savePic.js:
var savePic = function(req, callback){
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
fs = require('fs');
//When the following
//req.pipe(fs.createWriteStream('./test.png'));
//is not commented out, the correct image is stored to test.png, and
//the sequence after req.on("data"... starts
//(That sequence does not start at all when this is commented out..)
var fileId = new ObjectID();
var db = new Db('testDB', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
var gridStore = new GridStore(db, 'test', 'w');
//open
gridStore.open(function(err, gridStore) {
console.log("opened");
req.on("data", function (data) {
console.log("data recieved");
gridStore.write(data, function (err, gridStore) {
if (err) {
console.log("error writing file");
}
});
});
req.on("end", function () {
gridStore.close(function (err, gridStore) {
if (!err) {
console.log("The file has been stored to database.");
db.close();
}
});
});
req.pipe(gridStore);
});
});
callback(fileId);
};
module.exports = savePic;
Any help would be greatly appreciated!
gridfs-stream makes that pretty easy:
// `gfs` is a gridfs-stream instance
app.post('/picture', function(req, res) {
req.pipe(gfs.createWriteStream({
filename: 'test'
}));
res.send("Success!");
});
while #robertklep's answer is correct, I would like to add something to his answer. This code shows how you can send back the stored file's metadata.
app.post('/picture', function(req, res) {
req.pipe(gfs.createWriteStream({
filename: 'test'
}).on('close', function(savedFile){
console.log('file saved', savedFile);
return res.json({file: savedFile});
}));
})
This worked for me with mongoose:
var gfs = Grid(mongoose.connection.db, mongoose.mongo);
var writeStream = gfs.createWriteStream({
filename: name,
mode: 'w',
content_type: 'video/mp4'
});
writeStream.on('close', function() {
console.log('close event');
});
fs.createReadStream('uploads/' + name + '/' + name + '.mp4').pipe(writeStream);
console.log('stream.write: ' + name + '/' + name + '.mp4');
I am struggling a couple of days with getting the video on client side browser. That is what I tried so far:
var readstream = gfs.createReadStream({
filename: file.filename
});
readstream.on('data', function(data) {
res.write(data);
console.log(data);
});
readstream.on('end', function() {
res.end();
});
readstream.on('error', function (err) {
console.log('An error occurred!', err);
throw err;
});
My Data on MongoDB side looks like:
db.fs.chunks.find()
{ "_id" : ObjectId("5757e76df14741bf0391aaca"), "files_id" : ObjectId("5757e76df14741bf0391aac8"), "n" : 0, "data" : BinData(0,"AAAAIGZ0eXBpc29....
And the contentType is 'video/mp4':
logging on browser side prints this:
Object { 0: "�", 1: "�", 2: "�", 3: " ", 4: "f", 5: "t", 6: "y", 7: "p", 8: "i", 9: "s", 85003 more… }
Could someone please save my live? I hope you do not see my post as not convenient in this place.
Complete code to insert the txtfile in mongodb using gridfs in nodejs.This works well `
var mongoose=require("mongoose");
var gridfsstream=require("gridfs-stream");
var fs=require("fs");
mongoose.connect("mongodb://localhost:27017/testimage");
var conn=mongoose.connection;
gridfsstream.mongo=mongoose.mongo;
conn.once("open",function()
{
console.log("database connected successfully");
var gfs=gridfsstream(conn.db);
var writestream=gfs.createWriteStream({
filename:"danger.txt"
});
fs.createReadStream("sivakasi.txt").pipe(writestream);
writestream.on("close",function(file)
{
console.log(file.filename +"stored successfully into mongodb using gridfs");
});
writestream.on("error",function(file)
{
console.log(file.filename +"not stored into mongodb using gridfs");
});
});
conn.on("error",function()
{
console.log("database not connected try again!!!");
});
`
complete code to post the image from html to nodejs store that image in mongodb using gridfs system and display that image in server.This code works well.
var express=require("express");
var bodyparser=require("body-parser");
var multer=require("multer");
var app=express();
var upload = multer({ dest: '/tmp/'});
app.use(bodyparser.urlencoded({extended:false}));
app.post("/uploadimage",upload.single("file"),function(request,response)
{
var mongoose=require("mongoose");
var gridfsstream=require("gridfs-stream");
var fs=require("fs");
mongoose.connect("mongodb://localhost:27017/testimage");
var con=mongoose.connection;
gridfsstream.mongo=mongoose.mongo;
con.once("open",function()
{
console.log("test image database connected successfully");
var gfs=gridfsstream(con.db);
var readstream=fs.createReadStream(request.file.originalname);
var writestream=gfs.createWriteStream({
filename:"mentorpicthree.jpg"
});
readstream.pipe(writestream);
writestream.on("close",function()
{
console.log("image stored in mongodb database successfully");
fs.readFile(request.file.originalname,function(err,data)
{
if(err)
{
response.writeHead(404,{"Content-Type":"text/plain"});
console.log("error");
}
else
{
response.writeHead(200,{"Content-Type":"image/jpg"});
response.end(data);
}
});
});
writestream.on("error",function()
{
console.log("image not stored in mongodb database");
});
});
con.on("error",function()
{
console.log("database not connected try again!!!");
});
});
app.listen(8086,function()
{
console.log("server running on port 8086");
});
<html>
<head>
<title>FILE UPLOAD</title>
</head>
<body>
<p>Ryan Dhal</p>
<form action="http://127.0.0.1:8086/uploadimage" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="submit" value="UPLOAD">
</form>
</body>
</html>

Image Upload with GridFS using Node.js and Mongoose [duplicate]

I am trying to figure out how I can post an image directly to GridFS without storing it anywhere on the server as a temporary file first.
I am using Postman (chrome ext.) to post a file, and I manage to store this post as a file using:
req.pipe(fs.createWriteStream('./test.png'));
I am also able to store directly to GridFS from a readStream when the readStream is created from a file on the server. (see code)
I have the following files, saveFromReq.js which listens for the POST and basically just passes this on to the savePic.js.
saveFromReq.js:
var express = require('express');
var app = express();
var savePic = require('./savePic');
var fs = require('fs');
var GridStore = require('mongodb').GridStore;
var pic = './square.png';
var picID;
//When the following
//var pic = fs.createReadStream('./square.png', {autoClose: true});
//is not commented out, and 'req' is replaced with 'pic' in the savePic function,
//the file square.png is stored correctly to GridFS
app.post('/picture', function(req, res){
savePic(req, function(id){});
res.writeHead(200, {'Content-Type': 'text' });
res.end("Sucsess!\n");
});
app.listen(process.env.PORT || 3413);
savePic.js:
var savePic = function(req, callback){
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
fs = require('fs');
//When the following
//req.pipe(fs.createWriteStream('./test.png'));
//is not commented out, the correct image is stored to test.png, and
//the sequence after req.on("data"... starts
//(That sequence does not start at all when this is commented out..)
var fileId = new ObjectID();
var db = new Db('testDB', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
var gridStore = new GridStore(db, 'test', 'w');
//open
gridStore.open(function(err, gridStore) {
console.log("opened");
req.on("data", function (data) {
console.log("data recieved");
gridStore.write(data, function (err, gridStore) {
if (err) {
console.log("error writing file");
}
});
});
req.on("end", function () {
gridStore.close(function (err, gridStore) {
if (!err) {
console.log("The file has been stored to database.");
db.close();
}
});
});
req.pipe(gridStore);
});
});
callback(fileId);
};
module.exports = savePic;
Any help would be greatly appreciated!
gridfs-stream makes that pretty easy:
// `gfs` is a gridfs-stream instance
app.post('/picture', function(req, res) {
req.pipe(gfs.createWriteStream({
filename: 'test'
}));
res.send("Success!");
});
while #robertklep's answer is correct, I would like to add something to his answer. This code shows how you can send back the stored file's metadata.
app.post('/picture', function(req, res) {
req.pipe(gfs.createWriteStream({
filename: 'test'
}).on('close', function(savedFile){
console.log('file saved', savedFile);
return res.json({file: savedFile});
}));
})
This worked for me with mongoose:
var gfs = Grid(mongoose.connection.db, mongoose.mongo);
var writeStream = gfs.createWriteStream({
filename: name,
mode: 'w',
content_type: 'video/mp4'
});
writeStream.on('close', function() {
console.log('close event');
});
fs.createReadStream('uploads/' + name + '/' + name + '.mp4').pipe(writeStream);
console.log('stream.write: ' + name + '/' + name + '.mp4');
I am struggling a couple of days with getting the video on client side browser. That is what I tried so far:
var readstream = gfs.createReadStream({
filename: file.filename
});
readstream.on('data', function(data) {
res.write(data);
console.log(data);
});
readstream.on('end', function() {
res.end();
});
readstream.on('error', function (err) {
console.log('An error occurred!', err);
throw err;
});
My Data on MongoDB side looks like:
db.fs.chunks.find()
{ "_id" : ObjectId("5757e76df14741bf0391aaca"), "files_id" : ObjectId("5757e76df14741bf0391aac8"), "n" : 0, "data" : BinData(0,"AAAAIGZ0eXBpc29....
And the contentType is 'video/mp4':
logging on browser side prints this:
Object { 0: "�", 1: "�", 2: "�", 3: " ", 4: "f", 5: "t", 6: "y", 7: "p", 8: "i", 9: "s", 85003 more… }
Could someone please save my live? I hope you do not see my post as not convenient in this place.
Complete code to insert the txtfile in mongodb using gridfs in nodejs.This works well `
var mongoose=require("mongoose");
var gridfsstream=require("gridfs-stream");
var fs=require("fs");
mongoose.connect("mongodb://localhost:27017/testimage");
var conn=mongoose.connection;
gridfsstream.mongo=mongoose.mongo;
conn.once("open",function()
{
console.log("database connected successfully");
var gfs=gridfsstream(conn.db);
var writestream=gfs.createWriteStream({
filename:"danger.txt"
});
fs.createReadStream("sivakasi.txt").pipe(writestream);
writestream.on("close",function(file)
{
console.log(file.filename +"stored successfully into mongodb using gridfs");
});
writestream.on("error",function(file)
{
console.log(file.filename +"not stored into mongodb using gridfs");
});
});
conn.on("error",function()
{
console.log("database not connected try again!!!");
});
`
complete code to post the image from html to nodejs store that image in mongodb using gridfs system and display that image in server.This code works well.
var express=require("express");
var bodyparser=require("body-parser");
var multer=require("multer");
var app=express();
var upload = multer({ dest: '/tmp/'});
app.use(bodyparser.urlencoded({extended:false}));
app.post("/uploadimage",upload.single("file"),function(request,response)
{
var mongoose=require("mongoose");
var gridfsstream=require("gridfs-stream");
var fs=require("fs");
mongoose.connect("mongodb://localhost:27017/testimage");
var con=mongoose.connection;
gridfsstream.mongo=mongoose.mongo;
con.once("open",function()
{
console.log("test image database connected successfully");
var gfs=gridfsstream(con.db);
var readstream=fs.createReadStream(request.file.originalname);
var writestream=gfs.createWriteStream({
filename:"mentorpicthree.jpg"
});
readstream.pipe(writestream);
writestream.on("close",function()
{
console.log("image stored in mongodb database successfully");
fs.readFile(request.file.originalname,function(err,data)
{
if(err)
{
response.writeHead(404,{"Content-Type":"text/plain"});
console.log("error");
}
else
{
response.writeHead(200,{"Content-Type":"image/jpg"});
response.end(data);
}
});
});
writestream.on("error",function()
{
console.log("image not stored in mongodb database");
});
});
con.on("error",function()
{
console.log("database not connected try again!!!");
});
});
app.listen(8086,function()
{
console.log("server running on port 8086");
});
<html>
<head>
<title>FILE UPLOAD</title>
</head>
<body>
<p>Ryan Dhal</p>
<form action="http://127.0.0.1:8086/uploadimage" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="submit" value="UPLOAD">
</form>
</body>
</html>

Resources