Реализация Mongoose для отношений, связанных с документами, в MongoDB

Мне нужно сделать агрегационный запрос, используя связь, указанную в документе (не со встроенными документами). Я могу сделать этот запрос, используя оболочку mongo, но борюсь с его эквивалентной реализацией с использованием mongoose.

Я пробовал виртуальный метод заполнения, но он тоже возвращает пустые массивы. Вот код, который определяет контекст, а также мой запрос mongo. У меня есть отношения "один ко многим" между родительскими и дочерними документами.

    //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

person rohanmehto2    schedule 17.06.2019    source источник
comment
Покажите, пожалуйста, что вы пробовали с mongoose?   -  person Ravi Shankar Bharti    schedule 17.06.2019
comment
@RaviShankarBharti Я обновил фрагмент кода. Взгляни, пожалуйста.   -  person rohanmehto2    schedule 17.06.2019
comment
Amazon DocumentDB теперь поддерживает поиск $: aws.amazon.com/about-aws/whats-new/2019/10/   -  person Joseph Idziorek    schedule 17.10.2019


Ответы (1)


Реализация была очень четкой. Моя не работала из-за некоторых проблем с внедрением зависимостей. Хотя вот решение для справки:

Чтобы избежать использования массива идентификаторов ссылок при обращении к документам в коллекциях, рекомендуется использовать виртуальное заполнение.

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

band = await this.ArtistModel.findById(id).populate('members').exec()
person rohanmehto2    schedule 19.06.2019