0

I am new to the Mongoose and NodeJS world.

I have product document where I am storing category ids as shown below.

"reviewscount" : "2",
"overallrating" : "4.5",
"urlkey" : "strive-shoulder-pack",
"productid" : "2",
"categoryid" : "3,7,4",

Now wanted to fetch all the products belongs to one category based on category Id.

I tried below code, but getting empty result

Product.find({ "categoryid" : { "$in" : [ categoryId ] } }, function (err, products) {
console.log(products);
}

Am I doing it wrong way?

Charlie
  • 524
  • 2
  • 11
  • 31

2 Answers2

3

This would check whether the whole categoryid is equal to something in the in-array.

You basically got two options, the first (preferred) is to store your categoryid(s) as an array instead of csv and use a simple query as seens in this answer.

The second option is to manually (mongoose docs) parse the categoryid against your Id, but that wont scale very well (besides other problems).

Product.find({$where : 'this.categoryid.indexOf("' + categoryId + '") != -1'});

Community
  • 1
  • 1
CMR
  • 933
  • 1
  • 7
  • 8
1
Product.find({ "categoryid" : { "$in" : [ categoryId ] } }, function (err, products) {
console.log(products);
}

for this type query you need to convert in your schema.

"reviewscount" : "2",
"overallrating" : "4.5",
"urlkey" : "strive-shoulder-pack",
"productid" : "2",
"categoryid" : [3,7,4] // convert in your schema make categoryid:[Number]

to insert in categoryid use $addToSet with $each if you want unique value in array.

Manjeet Thakur
  • 2,288
  • 1
  • 16
  • 35