I am relatively new to nodejs. I am trying to save an image provided in a url (from api). After some online research, I decided to use createWriteStream method from nodejs to extract the image from url and save into the local directory. But I would like to be able to save directly to the mongodb. I am not able to figure out how to change the destination to a collection in mongodb.
My code snippet looks like below:
const fs = require('fs');
const request = require('request');
const Image = require('./models/Image');
const connectDB = require('./db');
connectDB();
const imageName = 'photo-' + Date.now();
const ext = 'jpg';
const url = 'https://some_path_for_image_by_api';
const getData = async (u, cb) => {
const myImage = await request(url).pipe(
fs.createWriteStream(`${imageName}.${ext}`)
);
cb(myImage);
};
const saveData = async (d) => {
const image = await new Image(d);
image.save(function (err, data) {
if (err) return console.error(err);
else return console.log('Image saved successfully', data);
});
};
getData(url, saveData);
Here is my Image schema definition:
const mongoose = require('mongoose');
const ImageSchema = new mongoose.Schema({
createdAt: {
type: Date,
default: Date.now,
},
img: {
data: Buffer,
contentType: String,
},
module.exports = mongoose.model('Image', ImageSchema);
With this code, the image is saved from a url to my root directory in the folder (not desired). The image document is created but just with ObjectId and version, not actual data. The goal is to be able to save the image retrieved from a url directly to mongodb as a document while not saving anything to the root directory. Maybe I am not doing the right way. How do I save it to the db instead of being saved to some folders in the directory or to the root directory?Any help and suggestion will be much appreciated.