Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

store images in mongoose

// file-controller.js

const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');

const router = express.Router();

const multerStorage = multer.memoryStorage();
const upload = multer({ storage: multerStorage, });

const imageSchema = mongoose.Schema({
    image: { data: Buffer, contentType: String },
}, { timestamps: true });

const ImageModel = mongoose.model('images', imageSchema);

router.post('/upload', upload.single('image'), async (req, res, next) => {
    const image = { data: new Buffer.from(req.file.buffer, 'base64'), contentType: req.file.mimetype }
    const savedImage = await ImageModel.create(image);
    res.send(savedImage);
});

router.get('/getImage/:id', async (req, res, next) => {
    const { id: _id } = req.params;
    // If you dont use lean(), you wont decode image as base64
    const image = await ImageModel.findOne({ _id }).lean().exec();
    res.send(image);
});

module.exports = router;
Comment

PREVIOUS NEXT
Code Example
Javascript :: mongoose delete 
Javascript :: react native float upto 2 digits 
Javascript :: export gcp credentials json file 
Javascript :: regex in mongo query 
Javascript :: netmask /24 
Javascript :: how to read a csv file in nodejs 
Javascript :: inheritance in javascript 
Javascript :: javascript array.find 
Javascript :: fetch js 
Javascript :: console shortcut chrome 
Javascript :: angular material remove outline 
Javascript :: node js and react js difference 
Javascript :: npm run start vs npm start 
Javascript :: django ajax body to json 
Javascript :: puppeteer set download path 
Javascript :: react 18 render 
Javascript :: js get json object keys 
Javascript :: check type of variable in javascript 
Javascript :: how to make a confirm popup in vue 
Javascript :: how to loop through something in node.js 
Javascript :: get current html file name javascript 
Javascript :: falsy values javascript 
Javascript :: debounce 
Javascript :: javascript check if property exists in object 
Javascript :: chart js delete old chart 
Javascript :: reverse method 
Javascript :: install bootstrap in react 
Javascript :: alert, react native alert 
Javascript :: convert int to timestanp js 
Javascript :: empty input field on click 
ADD CONTENT
Topic
Content
Source link
Name
9+7 =