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

210
Views
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 answers
Answer question

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