Node js, Mongoose query to match id with values stored as comma separated string

Question

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?


Show source
| javascript   | find   | node.js   | mongoose   | match   2017-01-04 08:01 2 Answers

Answers to Node js, Mongoose query to match id with values stored as comma separated string ( 2 )

  1. 2017-01-04 09:01

    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'});

  2. 2017-01-04 09:01
    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.

Leave a reply to - Node js, Mongoose query to match id with values stored as comma separated string

◀ Go back