【问题标题】:Insert multiple id documents in NodeJS to a collection mongoDB将 NodeJS 中的多个 id 文档插入到集合 mongoDB
【发布时间】:2017-05-08 09:04:41
【问题描述】:

我有一个用于发布一些文本字段和多个附件的表单。为此,我首先使用 gridfs 将附件保存到数据库,然后将它们的 id 插入到集合中。问题是我不知道访问附件的 ID。代码如下:

//Saving attachments to gridfs
var part1 = req.files.file1;
var part2 = req.files.file2;
var excel = req.files.fileExcel;
var writeImage1 = gfs.createWriteStream({
        filename: 'img_' + part1.name,
        mode: 'w',
        content_type: part1.mimetype
    });

    var writeImage2 = gfs.createWriteStream({
        filename: 'img_' + part2.name,
        mode: 'w',
        content_type: part2.mimetype
    });

    var writeExcel = gfs.createWriteStream({
        filename: 'excel_' + excel.name,
        mode: 'w',
        content_type: excel.mimetype
    });
    writeImage1.on ('close', function (image1) {
        console.log('Enter close writeImage1');
        console.log('Id image1 ', image1._id);
    });

    writeImage2.on('close', function (image2) {
        console.log('Enter close writeImage2');
        console.log('Id image2 ', image2._id);
    });
    writeExcel.on('close', function (file) {
        console.log('Enter close writeExcel');
        console.log('Id Excel ', file._id);
    });

    writeImage1.write(part1.data);
    writeImage1.end();

    writeImage2.write(part2.data);
    writeImage2.end();

    writeExcel.write(excel.data);
    writeExcel.end();
    //Save to posting collection in mongodb
    PostingSecond.create ({
        name: body.name,
        date: body.date,
        place: body.place,
        participant: body.participant,
        cause: body.cause,
        how: body.how,
        typePosting: body.typePosting,
        //I want to put id images here
        imageId: [image1Id, image2Id],
        //I want to put id file here
        fileId: excelId
    }, function (err, posting2) {
        if (err) {
            console.log(err);
            return res.status(400).json('Failed to save document');
        } else {
            res.json(posting2);
        }
    });

【问题讨论】:

    标签: node.js mongodb mongoose gridfs


    【解决方案1】:

    如果您使用multer 进行上传,那么您可以通过以下方式访问文件信息:

    https://github.com/expressjs/multer#file-information

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 2016-02-22
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多