如何通过Mongoose在MongoDB中存储二进制数据(PNG)



我正在一个网站上工作,这个网站有一个MEAN堆栈脚手架。io生成器:https://github.com/DaftMonk/generator-angular-fullstack,我试图以二进制形式上传一些图像文件到MongoDB。这是我的git项目的仓库:

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

我已经遵循@aheckmann的GIST到tee: https://gist.github.com/aheckmann/2408370,

但是我总是得到关于我的文件找不到的错误,即

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)

显然,问题中的png位于该目录中,我甚至尝试将目录移动到服务器端,但无济于事。

为什么找不到文件/目录入口点?

当涉及到在MongoDb中存储小文件时,许多依赖于Mongoose的答案也将依赖于使用GridFS。如果您可以简单地在MongoDB 中存储文件,而不依赖于GridFS和Mongoose,那么请尝试以下操作。(这个答案是在TypeScript,我认为是更容易阅读,但我可以张贴翻译JavaScript,如果需要的话。)

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

相关内容

  • 没有找到相关文章

最新更新