Question

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

    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);
        } );
    });

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

Was it helpful?

Solution

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})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top