上传和存储图像

hol*_*ard 13 mongoose mongodb node.js express

是的,我知道使用Node.js,Express和Mongoose上传图像以及如何使用node.js将图像存储在mongodb中?但那些解决方案不是我想要达到的目标.我希望能够使用Schema将图像存储在db(Mongodb with Mongoose)的二进制文件中.

那么,你知道任何使用组合Node.js,Express和Mongodb的应用程序吗?最好的情况是,如果有这个组合+ Jade的任何应用程序,但我想这要求很多.

提前致谢!

aar*_*ann 24

这是使用node/express/mongoose存储/显示带有mongodb的img 的快速示例.


Ven*_*h A 1

与 mongodb 一起提供的 GridFS 可能是一个选择。NodeJS(无论express还是jade)读写文件的代码如下:

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const fs = require('fs');

const mongodb= require('mongodb');

const connection = client.connect();

const dbName = 'myProject';
const connect = connection;
connect.then(() => {
  console.log('Connected successfully to server');
  const db = client.db(dbName);
  const bucket = new mongodb.GridFSBucket(db, { bucketName: 'myCustomBucket' });  
  fs.createReadStream('./test.txt').pipe(bucket.openUploadStream('test.txt'));
  bucket.openDownloadStreamByName('test.txt').pipe(fs.createWriteStream('./test2.txt'));
});
Run Code Online (Sandbox Code Playgroud)

它的作用类似于存储二进制的存储桶。如果需要一种集合的感觉,你可以在它上面使用 mongoose-gridfs