简体   繁体   中英

Mongoose - Populate Array With Reference Property

I have an array of Tags in my Post schema:

tags: [ { type: Schema.Types.ObjectId, ref: 'Tag' } ],

Tag looks like this:

{ name: String }

When I populate the tags array it is of course populated with tag object literals.

Is there a way I can instead have mongoose populate the array with only the name string from the tag?

I have tried only specifying the name, but then name is returned within an object literal.

Currently the population outputs:

[ { name: 'React' }, { name: 'JavaScript' } ]

But I would like it to be:

[ 'React', 'JavaScript']

Is there a way to do this with Mongoose ?

You can make use of 'post' Query Middleware function. This function will be triggered before the actual data is returned by Model.find() or Model.findOne() query. Inside the function you can use Array.map to transform the data to required format.

schema.post('findOne', function(doc) {
    // Transform the doc here.
    // Example: 
    // doc.tags = doc.tags.map(tag => tag.name);
});

You could also do the same for handling Model.find().

schema.post('find', function(docs) {
    // Transform the doc here.
    // Example: 
    // docs = docs.map(doc => {
    //     doc.tags = doc.tags.map(tag => tag.name);
    //     return doc;
    // });
});

You can use a virtual that returns a reduction of the tags array:

schema.virtual('plainTags').get(function () {
  // first, validate if the 'tags' path is populated
  if (!this.populated('tags')) {
    return this.tags
  }
  return this.tags.reduce(function(col, Tag) {
    col.push(Tag.name) return col
  }, [])
})

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