通过Node.js将图像插入MongoDB

时间:2022-05-05 02:34:09

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

我无法通过node.js将图像插入MongoDB。我的代码如下:

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?

我相信我所缺少的是我如何上传媒体,即fs.readFileSync(imgpath)。这是常见的方法,还是你推荐的更好的方法?

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?

或者,我愿意将图像存储在我的服务器上的文件夹中,只需将链接到图像的URL添加到我的数据库中的JSON对象。这样,我不必担心实际存储任何媒体到Mongo。一种方式提供比另一种更好的性能吗?

1 个解决方案

#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..

S3将是一个存储图像的好地方..它将有良好的性能..我们有一个应用程序,将图像存储在文件系统中...但它很难扩展...虽然性能很好..

#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..

S3将是一个存储图像的好地方..它将有良好的性能..我们有一个应用程序,将图像存储在文件系统中...但它很难扩展...虽然性能很好..