Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose: how to get string representation of query

I implementing module who automatically generate mongoose query by requested params, so for simplified test process I need to be able to get text representation of final query. How could I do that?

Like we have something like this:

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

I need to get something like this

"db.appmodels.where({id:777}).sort({date: -1})"
like image 288
silent_coder Avatar asked Jan 06 '14 21:01

silent_coder


People also ask

What does findOne return mongoose?

Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.

What is projection in mongoose?

In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

What is $or in mongoose?

The $or operator will match either of the condition with the documents. It does not matter if all the conditions match or not. The only condition matching the document is enough with the $or operator. In this article, we will discuss how to use $or operator in mongoose.

What is lean mongoose?

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents. In this tutorial, you'll learn more about the tradeoffs of using lean() . Using Lean.


1 Answers

You can set debug for mongoose, which would by default send the queries to console, to use the following:

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
})
like image 162
Alistair Nelson Avatar answered Oct 21 '22 14:10

Alistair Nelson