简体   繁体   中英

MongoDB - Populate GridFS files metadata in parent document

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM