Inserting an Image to MongoDB through Node.js

爷,独闯天下 提交于 2021-01-29 04:21:09

问题


I am having trouble inserting an image to MongoDB through node.js. My code is as follows:

var express  = require('express'),
mongoose = require('mongoose'),
fs = require('fs'),
Schema = mongoose.Schema;
app  = express(),
port = process.env.PORT || 3000;

var imagePath = '~\images\image1.png';

mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;

var contentSchema = new Schema({
    _id: Schema.ObjectId,
    date: {type: Date, default: Date.now},
    user_ip: Number,
    likes: Number,
    reports: Number,
    media: {data: Buffer, contentType: String}
})

var Content = mongoose.model('content', contentSchema);

var media = new Content({
    user_ip:12345,
    likes: 1400,
    reports: 0,
    media: fs.readFileSync(imagePath)
});

media.save(function(err,media){
    if (err) return console.error(err);
    console.dir(media);
});

I believe what I am missing is how I am trying to upload the media, i.e. fs.readFileSync(imgpath). Is this the common approach, or is there a better one that you recommend?

Alternatively, I am open to storing the images in a folder on my server and simply adding the URL linked to the images to the JSON object in my database. This way, I do not have to worry about actually storing any media into Mongo. Does one way provide better performance than the other?


回答1:


S3 Would be a good place to store images.. It will good performance.. We have a app that store images in file system... But it is difficult to scale... Performance is good though..




回答2:


If you are using images of format 'jpeg / png' and if they are less than 16mb, you can go with this github repo, its a module that helps saving images to mongodb easily, and without the complexity of GRIDFS, but in case if your files are greater than 16mb, you need to use GRIDFS,

This is the link for the github repo for images less than 16 mb (and also works well with react)

https://github.com/saran-surya/Mongo-Image-Converter



来源:https://stackoverflow.com/questions/30108711/inserting-an-image-to-mongodb-through-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!