猫鼬ObjectID作为对象键,然后填充

时间:2020-04-20 19:11:49

标签: mongodb mongoose mongoose-schema mongoose-populate objectid

我想用键作为另一个模型的objectID生成一个动态对象,然后填充动态键。例如,对于资产,我希望详细信息键为属性ID,但是在填充详细信息时,我希望键为attribute.name而不是_id

attributes:
{
    "_id":"5a23f5e6159f5c3438c75971",
    "name": "name"
    "type": "string"
}
{
    "_id":"5a23f60b159f5c3438c75972",
    "name": "age"
    "type": "number"
}

asset: 
{
    "_id":"5a23f5e6159f5c3438c75973",
    "type": "driver",
    "details": {
        "5a23f5e6159f5c3438c75971": "bob",
        "5a23f60b159f5c3438c75972": "50",
    }
}

populated asset: 
{
    "type": "driver",
    "details": {
        "name": "bob",
        "age": "50",
    }
}


const Attribute = new Schema({
    name: { type: String },
    type: {
        type: String,
        enum: ["string", "number", "mobile", "email"],
    }
})

const Asset = new Schema({
    type: { type: String },
    details: { [{ type: Schema.Types.ObjectId, ref: "Attribute"}]: String }
})

我可以将详细信息定义为details: { type: Schema.Types.Mixed },然后以属性ID作为键推入对象,但是我无法弄清楚如何填充它们以及如何正确定义资产模式以实现此目的。感谢有关此问题的任何帮助。

0 个答案:

没有答案