Mongoose gridfs-stream如何填充fs.file集合

我在nodejs中使用gridfs-stream模块来存储图像。

var db = require('config/db'); var Schema = require('mongoose').Schema; var schema = new Schema({ name: String, photo: Schema.Types.ObjectId // store file ObjectId }); var model = db.model('User', schema); model.findById('123...', function(err, user) { console.log(user.photo) // only returning file ObjectId console.log(user.photo.filename) // error }); 

我如何填充用户照片,以便我可以访问文件信息?

我知道我的数据库中有fs.files和fs.chunks。 但我应该为他们创build模式,以便我可以参考我的模型?

user.photo的types是Schema.Types.ObjectId。 因此,user.photo.filename将不存在。

您需要将映像file upload到gridfs,并获取fs.files集合中映像的fileId。 然后,您可以将user.photo设置为fs.files中文件的fileId。