代码之家  ›  专栏  ›  技术社区  ›  Tiocrash

如何在文档中聚合集合中的数据

  •  0
  • Tiocrash  · 技术社区  · 6 年前

    我有一个文件是这样建模的:

    { 
      _id: '1', 
      timeEntries: [
        { _id: '1',
          hours: '1'
        },
        { _id: '2',
          hours: '2'
        },
      ],
      totalHours: 3
    }
    

    我希望能够调用文档模型(虚拟字段?)上的方法,从文档的timeEntries中获取总小时数,而不是每次增加$addToSet。

    我该怎么做呢?

    更新

    另外,我的timeEntries实际上存储为一个引用数组。

    [ 5bcf5e53e452b800134787dd, 5bcf5f42e452b800134787de ]
    

    我需要一种方法来填充虚拟字段中的hours属性

    架构:

    const companyHourLogSchema = new Schema({
      dateOpened: {
      type: Date,
      default: Date.now,
     },
      dateClosed: {
      type: Date,
     },
      _id: {
      type: mongoose.Schema.ObjectId,
      auto: true,
     },
      company: {
      type: mongoose.Schema.ObjectId,
      ref: 'Company',
     },
      timeEntries: [{
      type: mongoose.Schema.ObjectId,
      ref: 'TimeEntry',
    }],
      title: {
      type: String,
      default: 'Current',
    },
    });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Mohammed Essehemy    6 年前

    因为时间条目被保存为引用,所以您需要使用mongoose populate 首先获取条目

    Model.find(/*your condition here*/).populate('timeEntries');
    


    virtuals 具体如下:

    schema.virtual('totalHours').get(function () {
         return this.timeEntries.reduce((agg,tiE) => agg + tiE.hours ,0);
    });
    

      console.log(modelInstance.totalHours);