Ric_Harvey
Ric_Harvey

Reputation: 63

mongoJS parsing JSON output

I'm playing with nodeJS and mongoJS. I've successfully queried the DB and returned a set of data:

    var databaseUrl = "redirect"; // "username:[email protected]/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);
        } );
    });

This returns this:

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

What I need to do now is select certain elements of the array such as redirect.weight or redirect.url.

Does mongoJS allow me to do this easily or is there a better way?

Any pointers greatly appreciated as ever!

Ric

Upvotes: 1

Views: 1140

Answers (1)

patalmypal
patalmypal

Reputation: 6712

MongoJS implements the mongo API. Calls to document contents use the dot notation.

So in the example above,

  var weight = RedirectURL.redirect.0.weight

// equal to 10, since it is the first item of the redirect array.

The same principle can be used with the find commands. So if you wish to find documents with weight = 10, use the following command

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

Upvotes: 1

Related Questions