I have ran into a problem with gridfs file upload.
Basically I get this bizzare error and I have yet not found solution for solving this problem.
Here is my code that should deal with file upload:
var path = require('path');
var router = require('express').Router();
var mongoose = require('mongoose');
var serverConfig = require('../config.js');
var multiparty = require('connect-multiparty')();
var fs = require('fs');
var GridFs = require('gridfs-stream');
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
router.post('/upload', multiparty, function(req, res){
console.log("file was posted");
var writestream = gfs.createWriteStream({
filename: req.files.file.name + Date.now(),
mode: 'w',
content_type: req.files.file.mimetype,
metadata: req.body
});
fs.createReadStream(req.files.file.path).pipe(writestream);
writestream.on('close', function(file){
res.status(200).json(file);
})
})
When trying to run my code, I get this error:
if (!db) throw new Error('missing db argument\nnew Grid(db, mongo)');
^
Error: missing db argument
new Grid(db, mongo)
Im using Mongoose version 4.11.12 and Gridfs-stream version 1.1.1
Does anybody know what should be done to get this thing working?
Looks like mongoose.connection.db is not pulling in the database name as it maybe missing on the connection string, your connection string should look like 'mongodb://username:password#host:port/database?options...' where database is the database you want to connect to.
alternatively you can just replace
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
with
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs("myDatabase", mongoDriver);
Related
I am trying to upload an image to my MongoDB. I'm using Mongoose, gridfs-stream and some other packages I was told to install (I'm relatively new to the whole MEAN ecosystem)
The request seems to go through fine, and the collections used for fs-stream do get auto added to my db, but the request always seems to time out with no error being returned and nothing being logged by nodemon.
Here is my code:
const router = require('express').Router();
const database = require('../config/database');
var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.connection;
var conn = mongoose.connection;
var gfs = new Grid(conn.db, mongoose.mongo);
router.get('/', function(req, res) {
res.send("Greetings!");
})
router.post('/img', function(req, res) {
var part = req.files.fileField;
var writeStream = gfs.createWriteStream({
filename: part.name,
mode: 'w',
content_type:part.mimetype
});
writeStream.on('close', function() {
return res.status(200).send({
message: 'Success'
});
writeStream.end();
})
});
I have tried running the mongodb locally, and on mlab, I have also tried images of varying sizes, most of which were less than 10MB and some less than 1MB. I'm at a loss of where to go from here as my research into the matter has also offered no answers.
I have been using gridfs-stream with older versions (<4.11.0) of mongoose with the following settings:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
mongoose.connect(connectionString);
grid.mongo = mongoose.mongo;
var gfs = grid(mongoose.connection.db);
All works fine with these settings. After the update to mongoose 4.11.11 the mongoose connection setting should be changed to (3rd line):
mongoose.connect(connectionString, {useMongoClient: true});
However, now mongoose.connection.db is no longer defined. How should the above code be changed to make it work again? Many thanks.
I found a solution which makes use of deasync and with minimal changes to all my existing code. However it does not look ideal so any suggestions will be greatly appreciated:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
var deasync = require("deasync");
//Connect to mongodb
mongoose.Promise = global.Promise;
mongoose.connect(connectionString, {useMongoClient: true});
//Get the connection setting
var getConnDb = function () {
var connDb;
mongoose.connection.then(function (conn) {
connDb = conn.db;
});
while (connDb === undefined) {
deasync.runLoopOnce();
}
return connDb;
};
//Set gridfs-stream connection
grid.mongo = db.mongo;
var gfs = grid(getConnDb());
Below is my code:The folder and filename is : gridFs/storeAudio.js.And the code is in storeAudio.js
var mongoose = require('mongoose');
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo=mongoose.mongo;
//establish mongoDB connection
var conn = mongoose.createConnection('mongodb://localhost:27017/aHolyBoly');
conn.once('open',function(){
// var gfs = Grid(conn.db);
// var db = new mongo.Db('aHolyBoly', new mongo.Server("127.0.0.1", 27017));
//var gfs = Grid(db, mongo);
var writeStream = gfs.createWriteStream({
filename:'song1.mp3'
});
fs.createReadStream('../list/hero.mp3').pipe(writeStream);
writeStream.on('close',function(file){
console.log(file.filename +'Written to db');
});
});
now in the cmd inside the gridFs file I am running the command node storeAudio.js to create the database with the collection.But the following error is displayed below in the screenshot attached:
Note:I ran the following commands before:npm install gridfs-stream,npm install mongoose.
Please let me know if any more inputs are needed.
I'm trying to set up this simnple NodeJS/mongodb app and I have my files structured like this:
server.js
|
+-routes/menu.js
+-routes/cases.js
In my server.js I declare my mongodb vars like this:
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
MongoClient = mongo.MongoClient,
Db = mongo.Db,
http = require('http'),
app = express(),
httpServer = http.createServer(app),
bodyParser = require('body-parser'),
server = new Server('host.mongohq.com', 10066, {auto_reconnect : true}),
db = new Db('myDb', server);
db.open(function(err, client) {
client.authenticate('myUser', 'myPassword', function(err, success) {
console.log('Authenticated');
});
});
var cases = require('./routes/cases'),
menu = require('./routes/menu');
But then when I try to reference my db var in eg menu.js like this:
db.collection(myCollection, function(err, collection) {});
I get an error that db is not defined.
Obviously I can move all the mongodb declarations down to both my menu.js and cases.js file but that's just very elegant. So how do I create one mongodb instance var and refer to it from my included files?
Thanks in advance...
You need to require server.js in your menu.js file.
Your db object isn't global. If you want it to be, declare it without var.
I am a newbie to node.js (but 10 years experience with C#)
I have the following code
var http = require("http");
var url = require("url");
var path = require('path');
var fs = require("fs");
var express = require("express");
var mongo = require("./node_modules/mongo");
var Server = mongo.Server;
var Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('mydb', server);
I get this exception:
Error: Cannot find module './node_modules/mongo'
at Function.Module._resolveFilename (module.js:338:15)
I also tried:
var mongo = require("mongo");
Try this instead:
var mongodb = require('mongodb');