MongoDB-在父文档中填充GridFS文件元数据 [英] MongoDB - Populate GridFS files metadata in parent document
问题描述
我将NodeJS与Express,MongoDB,Mongoose和GridFS一起用于上载和检索文件.
I am using NodeJS with Express, MongoDB, Mongoose and GridFS for uploading and retrieving files.
我想通过ID引用其他文档中的文件,并在查询其他文档时填充文件元数据.
I would like to reference files in other documents by ID and populate the files metadata when querying the other documents.
例如:如果我有一个用户"集合,其中包含这样的文档...
For example: If I have a collection "users" with documents like this ...
{
_id: ObjectId("554dfeb59e78d9081af2404f"),
name: "John Doe",
image: ObjectId("55b61ae329c44b483665bafc")
}
...我想做这样的事...
... I want to do somethig like this ...
User.findById(req.params.id)
.populate('image')
.exec(function(err, user) {...})
...这应该使我可以访问文件元数据-例如文件名...
... which should give me access to the files metadata - for example the filename ...
user.image.filename
有什么想法吗?
推荐答案
您可以为GridFS元数据集合定义一个架构,并在用户架构中引用它:
You can define a schema for the GridFS metadata collection and refer it in the User schema:
//define Model for metadata collection.
var GFS = mongoose.model("GFS", new Schema({}, {strict: false}), "fs.files" );
var UserSchema = Schema({
image: {type: Schema.Types.Object, ref: 'GFS' } // refer the model
});
var User = mongoose.model('User', UserSchema);
User.findById(req.params.id)
.populate('image') //populate
.exec(function(err, user) {...})
这篇关于MongoDB-在父文档中填充GridFS文件元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!