nodejs利用gridfs存文档到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) {
    });
};

//通过filenamemongo中将文档下载到磁盘中
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);
    });
};


原文:http://blog.csdn.net/u012437323/article/details/55253706

你可能感兴趣的:(数据库)