2

I'm trying to write a mongo script from the mongo shell, but I'm having a small problem. I'll let the code explain itself.

var shops = db.Shop.find({})

function printShopUrl(data) {
    var name, url;
    for (var i = 0; i < data.length(); i++) {
        name = data[i].name;
        url = db.Instance.findOne({name:name}).url;
        print(url);
    }
}

printShopUrl(shops)

So all i'm trying to do right now is just to print the url, but when I run this query I get an error.

TypeError: db.Instance.findOne({name:name}) has no properties (shell):1

Any idea what i'm doing wrong?

3
  • 1
    It looks like the query isn't finding anything, in which case it will return null. Print out the intermediate result db.Instance.findOne({name:name}) - what do you see? Commented Jun 10, 2011 at 1:17
  • thanks Mr. E, that was exactly the problem i had. i tried to answer my own question, but i didn't have enough point. so i'll post my solution here. .. i guess i can't, it's too long, but yeah, all i did was wrap it in a try catch and it works. Commented Jun 10, 2011 at 1:33
  • try catch is excessive just do if(result) print(result.url); Commented Jun 10, 2011 at 1:44

1 Answer 1

1

Main problem: the following may not return a value db.Instance.findOne({name:name}). Therefore when you add .url, you're trying to get a value from a null.

Try the following:

var obj = db.Instance.findOne({name:name});
if(obj && obj.url) { print(obj.url); }

You have the same potential issue with the name field (name = data[i].name).

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.