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

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

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 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