我有一个文件是这样建模的:
{
_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',
},
});