Reputation: 382
is it possible to reference another value other than the mongo generated _id?
User Model
uid: {type: String, required: true},
channel_pub: {type: String},
channel_groups: [{type: String}],
auth_key: {type: String},
channels: [{
name: {
type: String,
ref: 'channel'
}
}]
Channel Model
name: {type: String, required: true},
uid: [{
type: String,
ref: 'user',
required: true
}]
I am trying to reference the actual channel name in the user document.
Upvotes: 1
Views: 52
Reputation: 45402
You can do this with Populate Virtuals since 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'
});
Here the local field is channels.name
, the Channel
object will be populated in channels.data
.
For instance a find with channels.data
populated :
User.find({}).populate('channels.data').exec(function(error, res) {
console.log(JSON.stringify(res, null, 4));
});
will give :
[{
"_id": "588a82ff7fe89686fd2210b0",
"uid": "user1",
"channels": [{
"data": {
"_id": "588a80fd7fe89686fd2210a8",
"name": "channel1",
"uid": []
},
"name": "channel1"
}, {
"data": {
"_id": "588a80fd7fe89686fd2210a9",
"name": "channel2",
"uid": []
},
"name": "channel2"
}],
"id": "588a82ff7fe89686fd2210b0"
}
...
]
Upvotes: 2