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')
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);
}