nodejs利用gridfs存文档到mongo中

左丘楷
2023-12-01

最近开发一个web是用nodejs开发的,有个上传文档的功能
mongo链接端
首先npm install下载需要的模块
mongo中fs.files中有字段filesname,metadata,利用metadata作为文档的分类

var mongoose = require('mongoose');
var conn = mongoose.createConnection('mongodb://127.0.0.1:27017/NodeJS');
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var gfs = Grid(conn.db);
var path = require('path');
var util = require('util');
var urlencode = require('urlencode');
var mongooseSchema = new mongoose.Schema({
    filename: String,
    metadata: String,
    aliases: String
}, {collection: "fs.files", versionKey: ""});
var getFile = conn.model('getFile', mongooseSchema);
var fileUpload = {};

//根据metadata列出存mongo里的filename
fileUpload.findAllFiles = function (httpId, callback) {
    getFile.find({metadata: httpId}, {"filename": '1'}, function (err, docs) {
        if (err) {
            callback(err);
        } else {
            callback(null, docs);
        }
    })
};

//将文档存到mongo中
fileUpload.loadToMongo = function (name,httpId,callback) {
    var writestream = gfs.createWriteStream({
        filename: name,
        metadata:httpId
    });
    fs.createReadStream(files).pipe(writestream);
    writestream.on('close', function (file) {
    });
};
//通过filename从mongo中将文档下载到磁盘中
fileUpload.readFile = function (dir, name, callback) {
    var fs_write_stream = fs.createWriteStream("documents/" + dir + "/" + name);
    var readstream = gfs.createReadStream({
        filename: name
    });
    readstream.pipe(fs_write_stream);
    fs_write_stream.on('close', function () {
        callback(null);
    });
};
 类似资料: