mongoose非主键关联设置

Schema配置

const mongoose = require('mongoose');

const workSchema = new mongoose.Schema({
    uid: String        //用户uuid
}, {
    versionKey: false
});

workSchema.virtual('user', {            //虚拟键
    ref: 'User',                        //关联集合
    localField: 'uid',                  //本表字段
    foreignField: 'uuid',               //关联表中的字段
    justOne: true                       //是否唯一(一对多,多对多等)
});
mongoose.model('Work', workSchema);

查询:

model.Work.findOne(query_conditon, attributes).populate('user');

猜你喜欢

转载自www.cnblogs.com/Mr-Kahn/p/12762952.html