开发者

how to do a mongodb query in a mongodb function?

开发者 https://www.devze.com 2023-03-12 09:14 出处:网络
I\'m trying to write a mongo script from the mongo shell, but I\'m having a small problem. I开发者_如何学Python\'ll let the code explain itself.

I'm trying to write a mongo script from the mongo shell, but I'm having a small problem. I开发者_如何学Python'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?


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消