2017-02-12 65 views
0

我是javascript和MongoDB技术的新手。我试图根据一些条件(使用字段和值)查询“商业”集合。我需要使用日期字段(CreateDate)对查询结果进行排序。你能帮我吗?在此先感谢您的帮助!:) [Screenshot of my code attached here]如何根据查询结果的日期字段进行排序?

请注意:CreateDate字段中的值以YYYY-MM-DD格式(即2017-04-01)存储为字符串。

我得到了一个错误信息说

“无法读取属性 '排序' 的未定义”

,当我试图执行以下代码:

CODE:

exports.readDocument = function(collection, uniqueKey, field, value, callback) { 

    MongoClient.connect(url, function(err, db) { 
     assert.equal(null, err); 
     db.collection("Businesses").find({ 
       "Id": uniqueKey 
      }, { 
       [field]: value, 
       _id: 0 
      }, 
      function(err, result) { 
       if (result) { 
        result.toArray(function(err, items) { 
         console.log("toArray", items, err); 
        }); 
        callback(true); 
       } else { 
        callback(false); 
       } 
      }).sort({ 
      "Created Date": -1 
     }); 
     db.close(); 
    }); 
}; 
+3

您可以使用db.model.find()。sort() –

+0

进行排序,请以文本形式将代码添加到问题中。你也可以在这里看看:[mcve] –

回答

0

确保您使用的字段名称(“创建日期”)您的查询与Documents中使用的查询相同。最好使用小写字母数字和下划线作为字段名称。

0

您需要检查数据库名称是否正确。 同时确保您在排序前按预期得到结果。 我高度怀疑结果为空,这就是为什么你收到错误“未定义”的对象。

0

我认为你的语法在这里是错误的。你的语法应该是这样的

collection.find().sort({datefield: -1}, function(err, cursor){...}); 
0
db.collection("Businesses").find({ 
       "Id": uniqueKey 
      }, { 
       [field]: value, 
       _id: 0 
      }).sort({"Created Date": -1}).exec(function(err, result) { 
       if (result) { 
        result.toArray(function(err, items) { 
         console.log("toArray", items, err); 
        }); 
        callback(true); 
       } else { 
        callback(false); 
       } 
      }) 

尝试这种形式的猫鼬的驱动程序。

相关问题