node-mongodb icon indicating copy to clipboard operation
node-mongodb copied to clipboard

Retrieve a value from find()

Open bry4n opened this issue 15 years ago • 3 comments

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?

bry4n avatar Jan 28 '10 04:01 bry4n

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.

orlandov avatar Jan 28 '10 19:01 orlandov

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?

bry4n avatar Jan 28 '10 19:01 bry4n

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.

defrex avatar Mar 31 '10 16:03 defrex