0

I'm working on a site with a MEAN stack scaffolded from this yeoman.io generator: https://github.com/DaftMonk/generator-angular-fullstack, and I'm trying to upload some image files to MongoDB in binary form. Here is my git repo for the project:

https://github.com/peter-atlanta/personal-site

I've followed @aheckmann's GIST to a tee: https://gist.github.com/aheckmann/2408370,

But I keep getting errors about how my files can't be found, i.e.

Error: ENOENT, no such file or directory '../../client/assets/images/github.png'
    at Error (native)
    at Object.fs.openSync (fs.js:500:18)
    at Object.fs.readFileSync (fs.js:352:15)
    at Immediate.<anonymous> (/Users/peterward/petergrayward/blog/server/config/imageToMongo.js:43:21)
    at Immediate._onImmediate    (/Users/peterward/petergrayward/blog/node_modules/mongoose/node_modules/mquery/lib/utils.js:137:16)
    at processImmediate [as _immediateCallback] (timers.js:358:17)

Clearly, though, the png in question is located in that directory, and I've even tried moving the directory server-side to no avail.

Why can't a file/directory entry-point be found?

1 Answers1

1

When it comes to storing small files in MongoDb, many answers which rely on Mongoose will also depend on using GridFS. If you are okay with simply storing files in MongoDB without relying on GridFS and Mongoose then try the following. (This answer is in TypeScript which I think is easier to read, but I can post the transpiled JavaScript if need be.)

import mongodb = require("mongodb");
const URI = 'mongodb://...';
var dbPromise = new Promise<mongodb.Db>(function (resolve, reject) {
    mongodb.MongoClient.connect(URI, function (err, db) {
        resolve(db);
    });
});
import express = require("express");
var app = express();
import path = require("path");
import multer = require("multer");
var upload = multer({ dest: 'uploads/' });//saving files on filesystem seems to be a requirement
import fs = require("fs");    
interface IFile {
    name : string;
    binary : mongodb.Binary;
}

//<input type="file" type="file" id="png1" name="png1" />
app.post("/file-upload", upload.single("png1"), function (req, res) {
    let f = req.file;
    fs.readFile(f.path, function (err, buffer) {
            dbPromise.then(db => {
                let file : IFile = {
                    name: f.originalname,
                    binary: new mongodb.Binary(buffer)
                };
                db.collection('files').insertOne(file, function(err, result) {
                    if (err) {
                        res.json(500, err);
                    }
                    console.log(`${result.insertedId} ${result.insertedCount}`);
                });
            });
        })
});
T. Webster
  • 9,605
  • 6
  • 67
  • 94