Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
referencing documents only by the mongo objectID?

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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"
}
...
]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!