简体   繁体   中英

Insert multiple id documents in NodeJS to a collection mongoDB

I have a form that is used to post some text field and multiple attachments. To do that I save attachments first to database using gridfs, after that, I inserted their id to a collection. The issue is I don't have any idea to access the attachements's id. Here the code:

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

If you are using multer for the uploads then you can access the file information in this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM