InfoEngi InfoEngi - 23 days ago 7
JSON Question

How to save the result from collection.findone()

i have a simple question and i have read a lot of same issues here, but these are not exact the same or doesn't work for me :-(

I have a REST function called "addevent". The function gets a json input (req) and iterate through the json array to get some IDs to store them in an extra Array. That works perfect!

After that, the function should search in a mongodb for every single id and store some extra informations from this ID (e.g. the stored URL of this ID). With "console.log(result.link)" it works again perfect. But my problem is that, that i need to store this link in an extra Array (urlArray).

So how can i save the result of collection.findone(). I read something about, that findone() doesn't return a document, but a cursor? what does that mean? How do i have to handle that in my case?

That's the code:

exports.addevent = function(req, res) {

var ids = req.body;
var pArray = new Array();
var urlArray = new Array();

var eventName = ids.name;

for(var i in ids.photos) {
photoArray.push(ids.photos[i]);
var id = ids.photos[i]._id;

var collection = db.get().collection('photos');
collection.findOne({'_id':new mongo.ObjectID(id)},function(err, result) {
console.log(result.link);
}
)

}


Many thanks!

-------------------- Update --------------------

Ok, i think that has something to do with the asynch Callbacks. I found an article, but i don't know how to implement it in my case.

http://tobyho.com/2011/11/02/callbacks-in-loops/

And something about "promises" in javascript.

Answer

You can save the result of your search doing something like:

 var foundPhoto =  collection.find({_id':new mongo.ObjectID(id)}, function(err, photo){
                   if(!err){
                      return photo;
                    } else {
                        console.log(err)
                        return null;
                    }
                });

This way you get the return statement of your query in the "photo" variable.