Home > Enterprise >  openDownloadStream based on metadata in mongodb gridfs
openDownloadStream based on metadata in mongodb gridfs

Time:04-11

I have created GridFs bucket using metadata with page as field as below.

    const bucket = new GridFSBucket(mydb, {
          "DocumentImageFile",
    });
    fs.createReadStream(file)
      .pipe(
            bucket.openUploadStream(documentId.toString(), {
              metadata: {
                page: 1,
              },
            }),
          )
          .on('finish', () => {
             fs.unlink(file, () => {});
          });

Now I need to read based on page number. But read part doesn't seem to have filter for that. How can we read only chunks which has only page: 1 as metadata which I have taken during store.

const bucket = new GridFSBucket(projectContext.db, {
      bucketName: 'DocumentImageFile',
    });
    const strDocumentId: string = documentData.documentId.toString();
    const downloadStream = bucket.openDownloadStream(
      new ObjectID(strDocumentId),
    );

CodePudding user response:

Not sure if this is directly possible. For time being I have first queried for document id using metadata and then fetched using that id. So using 2 step process I was able to solve it.

const documentImage = await documentImageFileModel.findOne({
      filename: documentData.documentId,
      'metadata.page': 1,
    });

    const documentId = documentImage.id;

    const bucket = new GridFSBucket(projectContext.db, {
      bucketName: 'DocumentImageFile',
    });

    const downloadStream = bucket.openDownloadStream(new ObjectID(documentId));
  • Related