Question

I have a Product schema and a Category Schema.

var ProductSchema = new Schema({
    categories: [CategorySchema],
    createdDate: { type: Date, default: Date.now },
});

var CategorySchema = new Schema({
    name: String,
    createdDate: { type: Date, default: Date.now },
});

How to get the product which contains a particular category. How to write this query using mongoose.js?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top