用Mongoskin在每个产品的字段描述中查找一个MongoDB文档

这是我在MongoDB中的一个文档示例:

{ "_id": ObjectId('5525039895884d66710d0fc3'), "prid": "63527", "data": { "sku": "HF22-81639", "name": "Product Test", "ean": "8763900872512", "description": "This product is my first test", } } 

此search“描述”不起作用(这是我需要帮助的地方):

 app.get("/description/:id", auth, function(req, res, next) { req.collection.findOne({ "data.description": req.params.id }, function(e, result) { if(e) return next(e); res.send(result); }); }); 

我需要通过一个词来查找,集合中存在的所有产品都包含在描述字段中。

要通过单词查找,集合中存在的所有产品都包含在说明字段中,那么需要与大小写不敏感的正则expression式匹配。 您可以使用以下查询(作为示例):

 db.product.find({"data.description": /test/i}); 

其中/test/i表示不区分大小写,因此正则expression式匹配任何带有string"test"文本的描述字段。 等效的SQLexpression式如下所示:

 select * from product where description like '%test%' 

所以你可以在你的路由实现中使用相同的方法,使用find()方法返回所有匹配的文档,而不是只返回一个文档的findOne()

 app.get("/description/:id", auth, function(req, res, next) { req.collection.find({ "data.description": /req.params.id/i }, function(e, result) { if(e) return next(e); res.send(result); }); }); 

另一种select是在查找操作中使用$text运算符,因为它对使用文本索引索引的字段的内容执行文本search。 所以你要做的第一件事是在描述字段上创build一个文本索引:

 db.collection.createIndex( { "data.description": "text" } ) 

之后,您可以使用$ text操作符进行查询。 例如,下面的查询search术语咖啡:

 db.collection.find( { $text: { $search: "coffee" } } ) 

编辑

所有事情都是平等的,然后你可以更新你的路由实现在URL中使用查询string:

 app.get("/description", auth, function(req, res, next) { req.collection.find({ $text: { $search: req.params.q } }, function(e, result) { if(e) return next(e); res.send(result); }); }); 

您可以在浏览器中查询http://localhost/description?q=product