Search code examples
node.jsmongodbmongoosesubdocument

Mongoose search for an object's value in referenced property (subdocument)


I have two schemas:

var ShelfSchema = new Schema({
    ...
    tags: [{
        type: Schema.Types.ObjectId,
        ref: 'Tag'
    }]
});

var TagSchema = new Schema({
    name: {
        type: String,
        unique: true,
        required: true
    }
});

I would like to search for all Shelves where the tags array has a tag with a specific value.

I have tried using:

modelShelf.find({tags 'tags.name': 'mytag'})...

but it does not work. It always returns an empty array. Any idea? Looking at db each Shelf instance links only the objectID of the tags. I have used references because I need to work also with Tag(s) entities.


Solution

  • In mongoDB you essentially can't do this directly as queries target a single collection at a time. Recently there were added new features which allow some kind of join when using the aggregation framework but for your needs that is not necessary.
    From your schemas I see that the tags' names are unique so you can first fetch your desired tag with something like

    modelTag.find({name: 'mytag'})
    

    in order to get the tag's ID and then query your shelf collection for this tag ID

    modelShelf.find({tags: tagId})