3

I have created a stored javascript function in my MongoDB instance that counts the number of records in each collection. If I go to my mongo shell and type:

> db.eval("getTotals()");

it works as expected. if I try to call it through mongo like so:

totals = mongoose.connection.db.eval("getTotals()");
console.log(totals);

undefined gets logged. Does anyone see what I am doing wrong here?

6
  • 1
    it's not a good idea to use JS function in the server, they are the least performant way to do anything. Regular queries are always going to be faster and will have the advantage of not blocking other threads. Commented Feb 14, 2014 at 4:59
  • Why does mongo provide a way to do it then? Can you provide something that backs that up? Commented Feb 14, 2014 at 5:19
  • To provide a little context: getTotals() gets the document counts from 5 different collections. I had assumed calling one function on the server would be more performant than executing 5 different queries from mongoose. Why would the latter be faster? Commented Feb 14, 2014 at 5:24
  • @AbeMiessler: there are warnings on performance considerations of JavaScript queries eval() and $where in the MongoDB manual. If you can express your query using the standard MongoDB query operators, they will take advantage of indexes and enable much better concurrency. For your specific case of counts, there are further server-side optimisations in MongoDB 2.4+. JavaScript queries have greater flexibility at the expense of a performance/concurrency penalty. Commented Feb 14, 2014 at 15:11
  • @AbeMiessler why assume? Why not try it out? Don't forget that while the db.eval() is running, nothing else can be running where the five client queries can share read lock with other read queries, plus they will use indexes. Commented Feb 16, 2014 at 7:48

1 Answer 1

3

Most mongoose calls do not return in-line like this, but rather expect a callback to be passed in to process the results.

Completely untested, but you probably want something like:

mongoose.connection.db.eval("getTotals()", function(err, retVal) {
   console.log(retVal)
});

And in the real world, assign your result to a var outside of that scope or whatever you want to do.

Sign up to request clarification or add additional context in comments.

2 Comments

I found documentation for evaluation here: docs.mongodb.org/manual/reference/method/db.eval but there was no mention of a callback. Am I just looking in the wrong spot?
@abe that's the mongo shell. This is mongoose isn't it? Mongoose functions implement callbacks. Did you try. I'm on mobile so can't test.Or type properly for that matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.