19

Yes, I know about Uploading images using Node.js, Express, and Mongoose and How can I store images in mongodb with node.js? but the solution to those isn't what I want to achieve. I want to be able to use a Schema for the image to be stored in binary the db (Mongodb with Mongoose).

So, do you know of any applications that uses the combo Node.js, Express and Mongodb? The best would be if there were any applications with this combo + Jade, but I guess that's to much to ask for.

Thanks in advance!

Community
  • 1
  • 1
holyredbeard
  • 19,619
  • 32
  • 105
  • 171
  • 2
    You don't need anything special, you can grab the image base64 in the client and just send that to your api and store it as is in your db no problem. – Eric Uldall Apr 02 '22 at 05:25

3 Answers3

1

GridFS that comes along with mongodb might be an option. Code for nodeJS (irrespective of express or jade) to read and write a file is as below:

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const fs = require('fs');

const mongodb= require('mongodb');

const connection = client.connect();

const dbName = 'myProject';
const connect = connection;
connect.then(() => {
  console.log('Connected successfully to server');
  const db = client.db(dbName);
  const bucket = new mongodb.GridFSBucket(db, { bucketName: 'myCustomBucket' });  
  fs.createReadStream('./test.txt').pipe(bucket.openUploadStream('test.txt'));
  bucket.openDownloadStreamByName('test.txt').pipe(fs.createWriteStream('./test2.txt'));
});

It acts like a bucket kind of a store that stores binary. You can use mongoose-gridfs on top of it if a collection kind of a feel is needed

Venkatesh A
  • 1,875
  • 1
  • 19
  • 23
1

Create a schema that can accept BinaryData as the BSON type.

const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    profilePic: { type: Buffer, required: true }
});

const User = mongoose.model('User', userSchema);

Create a new user object

const newUser = {
    name: 'Bob',
    profilePic: fs.readFileSync('bobpicture.jpg'),
}

Save that object to your collection:

const newUserToSave = new User(newUser);
await newUserToSave.save();

You'll need the fs and mongoose packages as well for this example.

Stephen Taylor
  • 798
  • 7
  • 19
1

Multiple approaches can be used in NodeJS and mongoose to store images, but I found multer particularly interesting. You can store images and videos easily using multer, but keep in mind that the maximum file size in MongoDB is 25 MB per file. To store larger files, you can use the FOLDER instead of your MongoDB database. The following is an example of storing an image:

Note: The image size must be less than 25MB

index.js

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const multer = require("multer");

const app = express();
const port = 5000;

app.use(bodyParser.urlencoded({ extended: false }));

// IMPORTING SCHEMA
const ImageModel = require("./schema/imageModel");

// CONFIG
const ImageUpload = multer({
  limits: {
    fileSize: 1000000
  },
  fileFilter(req, file, cb) {
    if (!file.originalname.match(/\.(jpg|png|JPG|PNG|JPEG|jpeg)$/))
      return cb(new Error("This is not a correct format of the file"));
    cb(undefined, true);
  }
});

// ROUTE
app.post("/api/image", ImageUpload.single("image"), (req, res) => {
  const Image = req.file.buffer;
  const ID = uuidv4();
  const ImageData = new ImageModel({ ID, Image });
  ImageData.save((err, noerr) => {
    if (noerr) {
      res.sendStatus(200);
    }
  });
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

Check out this repository for more information.

Schema or ImageModel

const mongoose = require('mongoose');
const ImageSchema = new mongoose.Schema({
    Image:{
        type:Buffer,
        required:true,
    },
    ID:{
        type:String,
        required:true
    }
});
const ImageModel = mongoose.model('Image',ImageSchema);
module.exports = ImageModel;
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
porosh
  • 77
  • 1
  • 6