How to retrieve parent document based on sub-document's values?

3,969 views
Skip to first unread message

Jean-Bernard Moens

unread,
Mar 28, 2013, 12:20:03 PM3/28/13
to mongoo...@googlegroups.com

I have the following schema's:

var Child = new mongoose.Schema({
    'field': String,
    'value': String
  });

var Parent = new mongoose.Schema({
    'name': String,
    'children': [ Child ]
  });

I want to return the Parent for which one of the Child's corresponds to the following JSON object:

{ 'field': 'Family Name', 'value': 'Smith' }

I have tried this:

Parent.findOne({ 'children': { 'field': 'Family Name', 'value': 'Smith' } }, fn ...)

but it keeps on retrieving null.

My environment is: Node.js, Mongoose, MongoDB

Jean-Bernard Moens

unread,
Mar 28, 2013, 12:26:52 PM3/28/13
to mongoo...@googlegroups.com
UPDATE (but not solved yet)

Testing through the Mongo shell extension, I found out that the `Child` sub-documents have their own `_id`'s. If I add that `_id` to the query, it fetches the `parent` document. Now, I don't know in advance what that child `id` will be. So: how can I remove it from the sub-document query? (In other words, the above query literally looks for a JSON object with only two properties, while the sub-documents have three)

Jean-Bernard Moens

unread,
Mar 28, 2013, 12:38:47 PM3/28/13
to mongoo...@googlegroups.com
It seems the `$elemMatch` is the query operator to solve this problem. The actual query should be written as follows:

    Parent.findOne({ 'children': { $elemMatch: { 'field': 'Family Name', 'value': 'Smith' } } }, fn ...)

Reply all
Reply to author
Forward
0 new messages