5

When I run below stored JavaScript function I get errors:

> db.system.js.save({_id:"last_n_users", value: function(n){return db.users.find().sort({created_at:-1}).limit(n)}})
> db.eval("last_n_users(10)")

Here is the errors:

{ "value" : "DBQuery: store.users -> undefined" }

Why? Please help me?

1 Answer 1

11

The find() function returns a cursor, which can't be returned from JavaScript. The suggested workaround is to use toArray() to get an array return value.

Example ... before :

> use admin
switched to db admin
> db.system.js.save( { _id : "foo", value: function(n){return db.system.indexes.find().limit(n)} } )         
> db.eval( "foo(3)" )                                                                               
{ "value" : "DBQuery: admin.system.indexes -> undefined" }

just as you describe.
And after:

> db.system.js.save( { _id : "foo", value: function(n){return db.system.indexes.find().limit(n).toArray()} } )
> db.eval( "foo(3)" )                                                                                         
[
        {
                "name" : "_id_",
                "ns" : "admin.system.users",
                "key" : {
                        "_id" : 1
                }
        },
        {
                "name" : "user_1",
                "ns" : "admin.system.users",
                "key" : {
                        "user" : 1
                },
                "unique" : false
        },
        {
                "name" : "_id_",
                "ns" : "admin.whee",
                "key" : {
                        "_id" : 1
                },
                "v" : 0
        }
]
Sign up to request clarification or add additional context in comments.

Comments

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.