Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda