关闭或完成writestream事件未触发gridfs

时间:2017-03-29 18:07:45

标签: node.js express mongoose mean-stack gridfs-stream

我正在尝试使用mongoose和GridFS将文件写入MongoDB。 但是,gridfs writestream不会触发任何事件 - 关闭或完成。 此外,它甚至不会触发'错误事件'(以防万一有任何错误)。我的nodejs版本是4.4.5。 代码如下:

var mongoose = require('mongoose');
var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    fs = require('fs-extra');
var Regex = require("regex");
var fs = require('fs');
var path=require('path');
var grid =require("gridfs-stream");

var createRequirement = function (req, res) {
    var form = new formidable.IncomingForm({
        uploadDir: __dirname + '/upload'
    });
    form.multiples = true;
    form.keepExtensions = true;
    files = [],
    fields = [];
    form.on('field', function (field, value) {

    })

    form.on('file', function (field, file) {
            console.log(file.name);
            console.log('File uploaded : ' + file.path);
            grid.mongo = mongoose.mongo;
            var gfs = grid(db.db);
            var writestream = gfs.createWriteStream({
                filename: file.name,
                mode: 'w'
            });
            fs.createReadStream(file.path).pipe(writestream);
            //Below event is not fired.
            writestream.on('finish', function (file) {
                Company.findOne({
                    "users.userName": req.user.userName
                }).then(function (data) {
                    var company = data;
                    if (!company) {
                        return res.status(404).send({
                            'Not Found': 'Company data not found'
                        });
                    } else {

                        Contact.findByIdAndUpdate(
                            file._id, {
                                $push: {
                                    "attachments": {
                                        id: file._id
                                    }
                                }
                            }, {
                                safe: true,
                                upsert: true,
                                new: true
                            },
                            function (err, model) {
                                console.log(err);
                            }
                        );

                    }
                });
            })


});
form.parse(req);
    return;
};

1 个答案:

答案 0 :(得分:0)

经过多次尝试,我可以找出解决方案。 导致问题的是猫鼬连接。 gridfs-stream期望直接与Mongo-DB连接。 我希望他们能够简化事情并促进Mongoose连接的使用。