0

I have the following schema into my DB:

{ name: 'AFG',
  documents: [
    { name: 'doc1',
      templates: [
        { name: 'templ1',
          lastModified: <Date>},
        ...]
    },
    ...]
}

I am trying to make a query to look for the template with name 'templ1'. If I find it, I have to compare the last modification date with another and update the value. If I don't find it, I have to push it into the array.

I have tried to do it with the following query:

Country.findOne({name : countrySelected, documents : {$elemMatch: {name: documentSelected}}, 'documents.templates' : {$elemMatch: {name: templateSelected}}}, function(err, templateFound){...}

But I get the following error:

MongoError: cannot use the part (documents of documents.templates) to traverse the element ({documents: [ { name: "Passport", templates: [] }, { name: "Visa", templates: [] }, { name: "Driver's Licence", templates: [] }, { name: "Id Card", templates: [] }, { name: "Other", templates: [] } ]})

Someone knows how can I do it? Thanks!!

Pablo D
  • 393
  • 2
  • 6
  • 22
  • Please check a similar question: http://stackoverflow.com/questions/10043965/how-to-get-a-specific-embedded-document-inside-a-mongodb-collection – Alexander Suvorov Apr 18 '16 at 13:22

1 Answers1

0

You have to use the $in operator to search in arrays.

Country.findOne({
    name : countrySelected, 
    documents: {
        $elemMatch: {
            $and: [{
                name: {
                    $in: documentSelected //<-- must be array like ['doc1']
                }
            }, {
                'templates.name': {
                    $in: documentSelected //<-- must be array like ['tmpl1']
                 }
            }]
        }
    }
}, function(err, templateFound){
    //do something with err and templateFound
});

To update the LastModified date you need to update it in the callback function and save the document.

See this answer for nested array updates

Community
  • 1
  • 1
coderocket
  • 584
  • 3
  • 11