通过 Node.js 向 MongoDB 插入图像 [英] Inserting an Image to MongoDB through Node.js

查看:90
本文介绍了通过 Node.js 向 MongoDB 插入图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
});

我相信我缺少的是我尝试上传媒体的方式,即 fs.readFileSync(imgpath).这是常用的方法,还是有更好的推荐方法?

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?

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

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?

推荐答案

如果您使用的是 'jpeg/png' 格式的图像并且如果它们小于 16mb,您可以使用这个 github repo,它是一个有助于轻松将图片保存到 mongodb,没有 GRIDFS 的复杂性,但如果您的文件大于 16mb,则需要使用 GRIDFS,

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,

这是 github 存储库的链接,适用于小于 16 mb 的图像(也适用于 react)

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

这篇关于通过 Node.js 向 MongoDB 插入图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆