2

我在 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。但是我应该为他们创建架构以便我可以引用我的模型吗?

4

1 回答 1

1

user.photo 的类型为 Schema.Types.ObjectId。因此,user.photo.filename 将不存在。

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

于 2014-12-11T16:30:56.007 回答