我是 Mongoose 和 NodeJS 世界的新手。
我有一个产品文档,用于存储类别 ID,如下所示。
"reviewscount" : "2",
"overallrating" : "4.5",
"urlkey" : "strive-shoulder-pack",
"productid" : "2",
"categoryid" : "3,7,4",
现在想要根据类别 ID 获取属于一个类别的所有产品。
我尝试了下面的代码,但得到空结果
Product.find({ "categoryid" : { "$in" : [ categoryId ] } }, function (err, products) {
console.log(products);
}
我做错了吗?
最佳答案
这将检查整个categoryid
是否等于数组中的某些内容。
您基本上有两个选择,第一个(首选)是将您的 categoryid(s)
存储为数组而不是 csv,并使用简单的查询,如 this answer 中所示。 .
第二个选项是根据您的 ID 手动 ( mongoose docs ) 解析 categoryid
,但这不会很好地扩展 ( besides other problems )。
Product.find({$where : 'this.categoryid.indexOf("' +categoryId + '") != -1'});
关于javascript - Node js,Mongoose 查询将 id 与存储为逗号分隔字符串的值相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41458691/