Search code examples
node.jsmongodbmongoosegridfsnode-mongodb-native

nodejs mongodb Gridstore.exist infinite loop


I am trying to use GridStore of mongodb, I have a wierd infinite loop problem when I try the following code GridStore.exist(db, req.params.filename, function(err, result){

The following is the whole code and its debug output

var express = require('express'),
    mongoose = require('mongoose');

var app = express();

var db = mongoose.createConnection('mongodb://localhost/dev_gridfs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.errorHandler({dumpExceptions: true, showStack : true}));

app.get('/', function(req,res){
    console.log('main');
    res.send('<img src="/images/test.jpg"/>');
});

var GridStore = mongoose.mongo.GridStore;

app.get('/images/:filename', function(req, res){
    console.log('in get image: ' + req.params.filename);
    GridStore.exist(db, req.params.filename, function(err, result){
        console.log('in gridstore exist');
        if (err) {
            console.log(err);
            res.status(500);
            res.send();
        }
        if (result) { 
            console.log('file found');
            //TODO code for sending the file
            res.send('');
        } else {
            res.status(404);
            res.send();
        }
    });
});


app.listen(3000);
console.log('listening on 3000');

output printed is

main
in get image: test.jpg

Versions: [node:v0.8.11, express: 3.0.0rc4, mongoose: 3.2.1]

Any suggestions appreciated. I am not sure if this is a bug with node mongodb driver, I haven't found this as an issue in the driver issue tracker yet.


Solution

  • I made a mistake! GridStore expects MongoDB DB object and NOT Mongoose DB object. made the following code change and everything else works as expected!

    changed the following line shown in code above

    var db = mongoose.createConnection('mongodb://localhost/dev_gridfs');
    

    as

    var mongooseDb = mongoose.createConnection('mongodb://localhost/dev_gridfs');
    var db = mongooseDb.db;