【问题标题】:mongoJS parsing JSON outputmongoJS 解析 JSON 输出
【发布时间】:2012-05-16 12:49:14
【问题描述】:

我在玩 nodeJS 和 mongoJS。我已经成功查询了DB,返回了一组数据:

    var databaseUrl = "redirect"; // "username:password@example.com/mydb"
    var collections = ["things", "reports"]
    var db = require("mongojs").connect(databaseUrl, collections);

    db.things.find({url: "google.com"}, function(err, things) {
        if( err || !things) {
            console.log("URL not Found");
        }
        else things.forEach( function(RedirectURL) {
            console.log(RedirectURL);
        } );
    });

这会返回:

{ _id: 4fb2c304f2dc05fe12e8c428,
  url: 'google.com',
  redirect: 
   [ { url: 'www.goolge.com', weight: 10 },
     { url: 'www.google.co.uk', weight: 20 } ] }

我现在需要做的是选择数组的某些元素,例如redirect.weight 或redirect.url。

mongoJS 允许我轻松地做到这一点还是有更好的方法?

任何指针都非常感谢!

瑞克

【问题讨论】:

    标签: node.js mongodb mongojs


    【解决方案1】:

    MongoJS 实现了 mongo API。对文档内容的调用使用点符号。

    所以在上面的例子中,

      var weight = RedirectURL.redirect.0.weight
    

    // 等于 10,因为它是重定向数组的第一项。

    find 命令也可以使用相同的原理。因此,如果您想查找 weight = 10 的文档,请使用以下命令

      db.things.find({redirect.weight: 10})
    

    【讨论】:

    • 感谢 almypal,像你这样的人是我喜欢这个网站的原因!
    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2013-07-18
    相关资源
    最近更新 更多