Reputation: 3562
I have a User
schema and Product
schema. A user can add many products to the database.
Each Product keeps track of who added the product into the database.
Each User keeps track of the added items, by nesting the productSchema into the array
const productSchema = new Schema({
//...
addedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "users"
}
});
const userSchema = new Schema({
//...
addedItems: [productSchema]
});
mongoose.model("products", productSchema);
mongoose.model("users", userSchema);
Here's how I'm trying to populate the User's addedItems:
User.findOne({ _id: req.body.id })
.populate({
path: "addedItems",
match: { addedBy: req.body.id },
select: "_id"
})
What I'm trying to do:
Start off by finding the User by ID (no problem). Then populate the 'addedItems' array based on a condition. If 'addedBy' contains the SAME id as the current user then populate the product._id into the array.
Problem: When I check on the User's addedItems the array always shows up empty. Even though, there are multiple products in the DB with 'addedBy' with the matching id.
What am I doing wrong?
Upvotes: 0
Views: 147
Reputation: 467
I think your schema isn't designed to perform that query. My suggestions are:
const productSchema = new Schema({
//...
addedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
});
const userSchema = new Schema({
//...
addedItems: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}]
});
mongoose.model("Product", productSchema);
mongoose.model("User", userSchema);
Query to populate users added items
User.findOne({ _id: req.body.id }).populate('addedItems');
Upvotes: 1