使用Node.js/Express和Mongoose在MongoDB中存储图像

Bry*_*Cho 11 mongoose mongodb node.js

目前我使用angular-file-upload处理图像上传,我只是将图像保存到服务器的文件系统并在HTML中引用它.但是,我想尝试将图像直接存储在我为博客文章定义的Schema中的数据库中.

var blogSchema = new Schema({
    title: String,
    author: String,
    body: String,
    likes: { type: Number, default: 0 },
    comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
    date: { type: Date, default: Date.now },
    imageURL: String   // instead of this

    image: // store it directly
});

"imageURL: String" stores the path to the image.
Run Code Online (Sandbox Code Playgroud)

我想做到这一点,我可以只有一个存储图像本身的字段.我以为我可能只是像我已经上传的那样上传图像,而是在上传图像后将其转换为以二进制(或其他形式)存储在Mongo中.这可能吗?

谢谢!

Ale*_*lex 17

下面的示例显示了如何使用mongoose将图像上载到MongoDB.单击此链接以获取原始源

var express = require('express');
var fs = require('fs');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var imgPath = '/path/yourimage.png';

mongoose.connect('localhost', 'testing_storeImg');

var schema = new Schema({
    img: { data: Buffer, contentType: String }
});

var A = mongoose.model('A', schema);

mongoose.connection.on('open', function () {
  console.error('mongo is open');

  A.remove(function (err) {
    if (err) throw err;

    console.error('removed old docs');

    // store an img in binary in mongo
    var a = new A;
    a.img.data = fs.readFileSync(imgPath);
    a.img.contentType = 'image/png';
    a.save(function (err, a) {
      if (err) throw err;

      console.error('saved img to mongo');

      // start a demo server
      var server = express.createServer();
      server.get('/', function (req, res, next) {
        A.findById(a, function (err, doc) {
          if (err) return next(err);
          res.contentType(doc.img.contentType);
          res.send(doc.img.data);
        });
      });

      server.on('close', function () {
        console.error('dropping db');
        mongoose.connection.db.dropDatabase(function () {
          console.error('closing db connection');
          mongoose.connection.close();
        });
      });

      server.listen(3333, function (err) {
        var address = server.address();
        console.error('server listening on http://%s:%d', address.address, address.port);
        console.error('press CTRL+C to exit');
      });

      process.on('SIGINT', function () {
        server.close();
      });
    });
  });

});
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答!我能够使用它将文件保存到数据库.你知道如何使用Angular在客户端加载图像吗? (3认同)