仅通过mongo objectID引用文档?

时间:2017-01-26 22:24:28

标签: mongodb mongoose

是否可以引用mongo生成的_id以外的其他值?

用户模型

uid: {type: String, required: true},
channel_pub: {type: String},
channel_groups: [{type: String}],
auth_key: {type: String},
channels: [{
    name: {
        type: String,
        ref: 'channel'
    }
}] 

频道模型

name: {type: String, required: true},
uid: [{
    type: String,
    ref: 'user',
    required: true
}]

我正在尝试引用用户文档中的实际频道名称。

1 个答案:

答案 0 :(得分:2)

您可以使用Populate Virtuals执行此操作,因为mongoose 4.5.0:

var UserSchema = new mongoose.Schema({
    uid: { type: String, required: true }
}, {
    toJSON: {
        virtuals: true
    }
});

var ChannelSchema = new mongoose.Schema({
    name: { type: String, required: true },
    uid: [{
        type: String,
        ref: 'User',
        required: true
    }]
});

UserSchema.virtual('channels.data', {
    ref: 'Channel',
    localField: 'channels.name',
    foreignField: 'name'
});

此处的本地字段为channels.nameChannel对象将填入channels.data

例如填充channels.data的查找:

User.find({}).populate('channels.data').exec(function(error, res) {
    console.log(JSON.stringify(res, null, 4));
});

会给:

[{
    "_id": "588a82ff7fe89686fd2210b0",
    "uid": "user1",
    "channels": [{
        "data": {
            "_id": "588a80fd7fe89686fd2210a8",
            "name": "channel1",
            "uid": []
        },
        "name": "channel1"
    }, {
        "data": {
            "_id": "588a80fd7fe89686fd2210a9",
            "name": "channel2",
            "uid": []
        },
        "name": "channel2"
    }],
    "id": "588a82ff7fe89686fd2210b0"
}
...
]
相关问题