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

212
Visualizações
Select certain attributes from a document in mongodb using mongoose for dynamic referencing

Is it possible to select certain attributes from an object? for example excluding an email, logoUri...etc and personal info from a seller when populating dynamically?

Here is my messageSchema:

const messageSchema = mongoose.Schema({
  chatId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: "Chat",
  },
   ....
  // sender can be type of User or Seller
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    refPath: "senderType",
    required: true,
  },
  senderType: {
    type: String,
    required: true,
    enum: ["User", "Seller"],
  },
  readOn: { type: Date },
  read: Boolean, //}, {
  sentOn: {
    type: Date,
    default: Date.now,
  },
});

here is where I populate my schema:

const messages = await Message.find({ chatId: chatId })
      .populate("sender")
      .sort({
        sentOn: -1,
      });

since each has different attribute, is there a way to select depending on the type of model I am populating dynamically ? For example for user model:

.select('-email -logoUri') 

for seller model:

.select('-address')
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You'll probably want to set up use cases with selectors for each model the case is for

messageSelectors = {
  user: "-email -logoUri",
  seller: "-address",
  ...
}

Then, whenever you need to use selectors for messages, you can use selectors based on what your selecting for

function selectMessageAttributesFor(type, query){
  //verify type is in messageSelectors
  selected = await Messages.find(query).select(messageSelectors[type]).exec(callback);
}
about 4 years ago · Juan Pablo Isaza 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