首页 > 解决方案 > Mongo - 按不是 ObjectId 的值引用其他模式

问题描述

所以理论上,假设我有一个Posts模式并且想要链接在模式中创建它的用户。传统上我会放入模式

        posted_by: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User'
        }

假设用户有一个名为“user_serial_no”的字段,有没有办法可以使用这个其他字段(这将是唯一的)而不是 ObjectId 从帖子中引用用户?

标签: node.jsmongodbmongoose

解决方案


你正在寻找的是aggregate.lookup()

更多信息:https ://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-lookup

const result = await Posts.aggregate([
        {
            '$lookup': {
                'from': User.collection.name,
                'localField': 'posted_by',
                'foreignField': 'user_serial_no',
                'as': 'postByUser' // <= Mongoose will create a new field as a result for you 
            }
        },
        /*Other options like $projections & $unwind if needed*/
    ])

推荐阅读