Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda