如何find具体的价值是在关键还是不重要

我正在尝试在mongodb中查找数据。 我有这样的数据

{"name":"xxxx","product":"laptop,phone,mobile"} {"name":"yyyy","product":"phone,iphone,pendrive"} 

我正在试图find“电话”是在产品密钥,所以我已经在terminal试过这个命令

 db.collection.find({"product": /phone/}); 

它工作正常,但它不是在我的应用程序工作。所以我已经尝试了dynamic像在我的应用程序。

 var key=phone; var name="/"+key+"/"; collection.find({"product":name}).toArray(function(err,result) { console.log(result.length); }); 

但我总是只有0长度,所以如何dynamic地使用它?

你每次都在寻找2个不同的东西。 在terminal中,您正在使用正则expression式searchphone这个词的出现。 在您的应用程序中,您正在searchstring文字'/ phone /'的出现。 你需要在你的应用程序的MongoDB查询中进行正则expression式search:

 var key = 'phone'; collection.find({"product":{ $regex: key }).toArray(function(err,result) ... 
 var key = 'phone'; var reg = RegExp('.*'+key+'.*','gi'); collection.find({"product":{ $regex: reg }).toArray(function(err,result){ } 

如果你的钥匙出现在string之间,这也将工作