I know this question is old. But I stumbled upon this as I was looking for a solution to a similar problem. So, this is for future knowledge seekers!
Ankur's answer will help if you want the referals created inside the user document.
Ex:
{
_id: 'XXX',
...
referals: [{_id:'yyy',email: ''}]
}
I think Using Mongoose Virtuals will help scale the application better. With virtuals, you wouldn't have to create duplicate records.
So if you decide to use Mongoose Virtuals, your schema would look like this
var userSchema = new mongoose.Schema({
_id: { type: Schema.ObjectId },
email: { type: String, unique: true },
ipAddress: { type: String },
referedBy: {
type: mongoose.Schema.Types.ObjectId, ref: 'User'
},
redeem_token: {type: String, unique: true}
});
userSchema.virtuals('refereals',{
ref: 'User',
localField: '_id',
foreignField: 'referedBy',
justOne: false,
},{ toJSON: { virtuals: true } }); /* toJSON option is set because virtual fields are not included in toJSON output by default. So, if you don't set this option, and call User.find().populate('refereals'), you won't get anything in refereals */
var User = mongoose.model('User', userSchema);
Hope this helps. If I am wrong, please correct me as I am new to this.