Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve a value from find() #3

Open
bry4n opened this issue Jan 28, 2010 · 3 comments
Open

Retrieve a value from find() #3

bry4n opened this issue Jan 28, 2010 · 3 comments

Comments

@bry4n
Copy link

bry4n commented Jan 28, 2010

I could not figure out how to retrieve a value from MongoDB#find()

Example:

examples.insert({ name: "Guest" })
results = examples.find()

or

examples.insert({ name: "Guest" })
results = examples.find().addCallback(function(results) {
    return results
})

I wanted to do something like that instead of this

var results = ""
examples.find().addCallback(function(stuffs) { results = stuffs })
p(results) #=> ""

Last example is acting like variable results is static and unable to modify it.

Any thought?

@orlandov
Copy link
Owner

Hey Bry4n, this is behaviour is definately by design. In your examples, results is the retrieved value. Since Node.js is asynchronous,the synchronous style of "do something, wait, then assign the value to my variable" won't work here. Checkout the README; what you probably want is

examples.insert({ name: "Guest" });
examples.find().addCallback(function (result) {
    // do something with result here
});

It takes a while to get used to this style, but trust me, it's really powerful. Your program can be doing other stuff (instead of idly waiting) while waiting on IO.

@bry4n
Copy link
Author

bry4n commented Jan 28, 2010

Thanks for the answer. The reason I asked for solution because I am using visionmedia's express (node.js web framework)

I tried this in express:

get("/set/:name", function() {
    examples.insert({ name: this.param("name") })
}); // works perfectly

get("/get/:name", function() {
   examples.find().addCallback(function (result) {
        return result;
   });
}); // doesn't work because express can't read the value from return

Unfortunately, the browser is hanging and asking for the return of value.

Any thought?

@defrex
Copy link

defrex commented Mar 31, 2010

I don't know that framework, but it should provide an asynchronous way to complete the request. Glancing at it's docs, it looks like it uses 'this'. It'd probably be something like:
get("/get/:name", function() {
var that = this;
examples.find().addCallback(function (result) {
that.finish(result);
});
});
Or something like that. If there isn't an async option instead of return, basically the whole framework is missing the point of node.js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants