+ 1

Exclude some sub-properties using mongoose

Hi every one. I'm using mongoose and I want to exclude two sub properties (description and userId) from final result. If this is the code 👇, how can I exclude this two properties (after populate it)? As you see, I used select method for this reason, but the result still includes these two properties. How can I resolve this? thanks for your help. https://sololearn.com/compiler-playground/cpz08nq36DZX/?ref=app

10th Feb 2025, 4:11 PM
Hamidreza Abolfathi
Hamidreza Abolfathi - avatar
2 Answers
+ 5
Hamidreza Abolfathi I believe -> To exclude the description and userId properties after populating a field in Mongoose, you can use the select method in your .populate() call, but make sure you're excluding the fields correctly. const getOrders = async (userId) => { try { const orders = await Order.find({ userId: userId }) .populate("items.product", "-description -userId") // Exclude 'description' and 'userId' .exec(); console.log(orders); return orders; } catch (err) { console.error(err); throw err; } };
10th Feb 2025, 11:24 PM
BroFar
BroFar - avatar
+ 1
I realized my mistake. Thanks BroFar .
11th Feb 2025, 7:25 AM
Hamidreza Abolfathi
Hamidreza Abolfathi - avatar