【问题标题】:Mongoose - Populate Array With Reference PropertyMongoose - 使用引用属性填充数组
【发布时间】:2017-05-07 09:40:37
【问题描述】:

我的帖子架构中有一组标签:

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

标签如下所示:

{ name: String }

当我填充 tags 数组时,它当然会填充标签对象文字。

有没有办法让猫鼬只用标签中的name 字符串填充数组?

我尝试只指定名称,但随后在对象文字中返回 name

目前人口产出:

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

但我希望它是:

[ 'React', 'JavaScript']

有没有办法用 Mongoose 做到这一点?

【问题讨论】:

  • 您的架构似乎应该改为[{type: String}],这样您就不会一直与库作斗争。您是否有任何理由需要架构中的 ObjectIds 但实际上保存了字符串?

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您可以使用'post'Query Middleware 功能。此函数将在 Model.find() 或 Model.findOne() 查询返回实际数据之前触发。在函数内部,您可以使用 Array.map 将数据转换为所需的格式。

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

您也可以对 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;
    // });
});

【讨论】:

    【解决方案2】:

    您可以使用一个虚拟的返回标签数组的缩减:

    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
      }, [])
    })
    

    【讨论】:

      猜你喜欢
      • 2014-10-27
      • 1970-01-01
      • 2016-05-31
      • 2018-06-07
      • 2022-06-14
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2014-12-05
      相关资源
      最近更新 更多