InfoEngi InfoEngi - 1 year ago 58
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(" 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 =;

for(var i in {
var id =[i]._id;

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


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.

And something about "promises" in javascript.

Answer Source

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download