无法使用 function(req, res, next, id) mongoose ( mongodb ) 中的动态 id 字段进行查询

Unable to query using the dynamic id field in function(req, res, next, id) mongoose ( mongodb )

我正在使用 mean js,我正在尝试通过 angularjs、

中的服务调用来查询 mongodb
   var Priority = 'Left_VM_P'; 
   url = currentUrl+"/api/queryPrioritySearch/"+Priority;

查询仅在

时有效
Property.find({ Left_VM_P : true }).exec(function(err, properties) {  

当我尝试用 id 的值替换变量 Left_VM_P 时,它没有响应。

exports.queryPrioritySearch = function(req, res, next, id) { 
console.log('id = ', id); 
Property.find({ id : true }).exec(function(err, properties) {           

根据控制台日志记录 id 的值变为

id =  Left_VM_P

这是示例 mongo 对象。

    { 
      "Left_VM_P": true,
      "Later_P": true,
      "High_P": true,
      "last_date_call_was_made": "-",
      "call_priority": "-"
    }

另外,当我在 mongo shell 中搜索时,它的 returns 值是正确的。

> db.properties.find({"Left_VM_P" : true}).count();
3

我认为您不能将变量放在 mongodb 查询的左侧。 mongodb 始终将左侧视为字符串的字段名称。所以

Property.find({ Left_VM_P : true }).exec(function(err, properties) 

会起作用,因为它将 left_VM_P 视为字符串,所以它就像 "Left_VM_P": true

Property.find({ id : true }) 的情况下,它将其视为字符串 "id":true

但您需要动态名称代替 id,因此您可以尝试此解决方案

var dynamicId={};
dynamicId[id]=true;
Property.find(dynamicId).exec(function(err, properties)

希望对您有所帮助:)

完整版如下:

exports.queryPrioritySearch = function(req, res, next, id) { 
var id_2  = id; 

var dynamicId={};
dynamicId[id_2]=true;


Property.find(dynamicId).exec(function(err, properties) {