Presuming that you have a model definition for Product
based on the ProductSchema
definition then the general syntax is not much different from a standard mongoDB .find()
query:
var categoryId; // As whatever the desired value of the ObjectId is
Product.find({ "categories._id": categoryId }, function(err,product) {
// Work with found document or err object here
});
So this is just a simple "dot notation" form of the query in order to reference the sub-document element.
Of course your schema structure also appears to be based on embedded documents so that means you should be able to access any of the other properties of that schema as well:
Product.find({ "categories.name": "category name" }, function(err,product) {
// Work with found document or err object here
});
For solutions that have the CategorySchema
objects within their own model collection, there is also the .poulate()
method which provides an effective, if not quite as efficient alternative to embedding where embedding is not practical.