MongoDB - Populate GridFS files metadata in parent document

左心房为你撑大大i 提交于 2019-12-23 01:13:49

问题


I am using NodeJS with Express, MongoDB, Mongoose and GridFS for uploading and retrieving files.

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

Any ideas?


回答1:


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) {...})


来源:https://stackoverflow.com/questions/32073183/mongodb-populate-gridfs-files-metadata-in-parent-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!