Search code examples
mongodbmongoosemongoose-populateaws-documentdb-mongoapiaws-documentdb

Mongoose implementation for Document Referenced Relationship in MongoDB


I need to make a aggregation query using document referenced relationship (not with embedded documents). I'm able to make that query using the mongo shell, but struggling with its equivalent implementation using mongoose.

I have tried the virtual populate method, but that too is returning empty arrays. Here's some code which define the context and also my mongo query. I am having a one to many relationship between the parent and child documents.

    //Parent Document
    db.artists.insert(
        {
            _id : 4,
            artistname : "Rush"
        }
    )

    //Child Documents
    db.musicians.insert(
        {
            _id : 9,
            name : "Geddy Lee",
            instrument : [ "Bass", "Vocals", "Keyboards" ],
            artist_id : 4
        }
    )
    db.musicians.insert(
        {
            _id : 10,
            name : "Alex Lifeson",
            instrument : [ "Guitar", "Backing Vocals" ],
            artist_id : 4
        }
    )
    db.musicians.insert(
        {
            _id : 11,
            name : "Neil Peart",
            instrument : "Drums",
            artist_id : 4
        }
    )

    //Query
    db.artists.aggregate([
        {
          $lookup:
            {
              from: "musicians",
              localField: "_id",
              foreignField: "artist_id",
              as: "band_members"
            }
       },
       { $match : { artistname : "Rush" } }
    ]).pretty()

    //Result
    {
        "_id" : 4,
        "artistname" : "Rush",
        "band_members" : [
            {
                "_id" : 9,
                "name" : "Geddy Lee",
                "instrument" : [
                    "Bass",
                    "Vocals",
                    "Keyboards"
                ],
                "artist_id" : 4
            },
            {
                "_id" : 10,
                "name" : "Alex Lifeson",
                "instrument" : [
                    "Guitar",
                    "Backing Vocals"
                ],
                "artist_id" : 4
            },
            {
                "_id" : 11,
                "name" : "Neil Peart",
                "instrument" : "Drums",
                "artist_id" : 4
            }
        ]
    }

//I've tried using populate, as well as aggregate. Here are both the implementations:

//Using populate
ArtistSchema.virtual('members', {
   ref: 'MusicianCollection',
   localField: '_id',
   foreignField: 'artist_id',
   justOne: false,
   options: {limit: 5}
})

this.ArtistModel.findById(id).populate('members').exec((err, data) => {
      if (err) console.log(err)
      else artist = data
    })

//in this i get a features array, but its empty


//Using aggregate
let artist = await this.ArtistModel.aggregate([
     { $match: { _id: id} },
     { $lookup: {
       from: 'Musicians',
       localField: '_id',
       foreignField: 'artist_id',
       as: 'members'
     } }
   ]);

//in this the request times out

Solution

  • The implementation was very clear. Mine wasn't working due to some dependency injection issues. Although heres the solution for reference:

    To avoid using an array of reference ids when referencing documents across collections, virtual populate is the way to go.

    ArtistSchema.virtual('members', {
       ref: 'MusicianCollection',
       localField: '_id',
       foreignField: 'artist_id',
       justOne: false,
       options: {limit: 5}
    })
    
    band = await this.ArtistModel.findById(id).populate('members').exec()