Home > OS >  While using .populate() in mongoose how to fetch and add, ObjectIds with additional properties to ar
While using .populate() in mongoose how to fetch and add, ObjectIds with additional properties to ar

Time:12-25

While using .populate() in mongoose how to fetch and add, ObjectIds with additional properties to array(returned by .populate()) whose document in the collection no longer exists?

My question is regarding MongoDB mongoose .populate() I have 2 collections:

users:

        likedSongs: [objectId()]
        playlists:
            songs: [ObjectId()}
        creator:
            songs: [ObjectId()]

songs:

        _id: ObjectId() ( Default )

There are other fields but irrelevant to this question

a user uA is a creator of song sA and some other users [oU] have added the sA to their likedSongs and playlists. while adding a new song and while removing a song, I also add and remove songId from uA.creator, but it is not possible for me to remove songId of sA from every single user [oU]'s likedSongs and playlist. 'cause it will increase the load on the server.

So what I want to do is while populating the ObjectIds, I want to add an "empty" property to every songId which was not found, and then ask the user in the frontend if he wants to remove the song that "no longer exists", If so then make an API call from there to remove it

But the problem is, after .populate() mongoose only returns an array of songs whose ObjectIds were matched, I don't know how to fetch the ObjectIds whose song no longer exists, and add them with the array which I got from .populate()

I know, I'm not very good at explaining problems, but if you can understand please give a solution. Is there any method or function in mongoose which I can use?

CodePudding user response:

That is not possible. During .populate(), MongoDB will actually go and make another database call to fetch additional information from the other collection. Since you already deleted some documents, MongoDB can not find them during population.

What you can do it refactoring your schema model, so instead of saving only ObjectIds of each song, you would in addition store some other properties for display purposes (song name, song duration...). Then, even when song is removed, you can still display something to the user.

However, if original song document is changed, you would still need to updated these additional information for all users.

  • Related