mongoose:如何获取查询的string表示

我实现的模块自动生成mongoose查询所需的参数,所以为了简化testing过程,我需要能够得到最终查询的文本表示。 我怎么能这样做?

就像我们有这样的事情:

var q = AppModel.find({id:777}).sort({date:-1})

我需要得到这样的东西

 "db.appmodels.where({id:777}).sort({date: -1})" 

您可以设置mongoose的debugging,默认情况下将查询发送到控制台,使用以下命令:

 mongoose.set('debug', function (collectionName, method, query, doc) { // Here query is what you are looking for. // so whatever you want to do with the query // would be done in here }) 

给定查询对象q您可以使用其字段重build查询,即q._conditionsq._update 。 这是没有文档,但可以轻松地破解版本之间的Mongoose(在Mongoose 4.0.4testing)。