猫鼬异步访问器

时间:2020-06-25 05:14:12

标签: node.js mongodb mongoose mongoose-schema

考虑架构

const Person = Schema({
    name: String,
    pets: {
       type: [Schema.Types.ObjectId],
       ref: 'Pets'
    }
})

const Pet = Schema({
    name: String,
    color: String
})

Person.findBy(personId)上如何返回以下内容而不是ID数组?

{
    name: 'John Doe',
    pets: [
        { name: 'Lilah', color: 'white' },
        { name: 'Hanna', color: 'brown' }
    ]
}

我试图使用猫鼬异步访问器

const Person = Schema ({
    ...
    
     pets: {
         type: [Schema.Types.ObjectId],
         ref: 'Pets',
         get: async pets => Pets.find({ '_id': { $id: pets} })
      }
    
    ...
})

但是感觉像是工程过度(每次访问属性时都会运行该函数)

0 个答案:

没有答案
相关问题