Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an Embedded Document by a specific property in Mongoose, Node.js, MongodDB

For this app, I'm using Node.js, MongoDB, Mongoose & Express

So I have a Param Object that contains an array of Pivots, and I want to read certain data from the pivots as outlined below

---in models.js-------------------------
    var Pivot = new Schema({
    value : String
  , destination : String
  , counter : Number
 });


var Param = new Schema({
    title : String
  , desc : String
  , pivots : [Pivot]
});


------------- in main.js --------------

var Param = db.model('Param');


app.get('/:title/:value', function(req, res){
    Param.findOne({"title":req.param('title')}, function(err, record){
           console.log(record.pivots);
           record.pivots.find({"value":req.param('value')}, function(err, m_pivot){
                    pivot.counter++;
                    res.redirect(m_pivot.destination);
           });
           record.save();
    });
});

I know that the code works until console.log(record.pivots), since i got a doc collection with the right pivot documents inside.

However, there does not seem to be a find method to let me match an embedded document by the 'value' property defined in the schema. Is it possible to search through this array of embedded documents using .find() or .findOne() , and if not, is there some easy way to access it through mongoose?

like image 483
varunsrin Avatar asked Apr 24 '11 20:04

varunsrin


1 Answers

varunsrin,

This should do it

app.get('/:title/:value', function(req, res) {
  Param.findOne({'pivots.value': req.param('value'), "title":req.param('title')}},
                function(err, record) {
                  record.pivot.counter++;
                  res.redirect(m_pivot.destination);  
                 record.save();
               });
});

Note the pluralization of the query to match the field name in your schema

like image 143
deedubs Avatar answered Sep 28 '22 00:09

deedubs