Home > Software design >  How do I pull an item from array in Mongoose?
How do I pull an item from array in Mongoose?

Time:12-02

I'm trying to remove an item from session_users. The purpose of users is to have a reference to an user that has joined a session. session_users on the other hand have a reference to the user and some data that is only valid during that session.

I get session and user as a reference for that session and user I want to remove, which does work fine in other code.

Here is an example of a session exported from MongoDB Compass:

{
    "_id": {
        "$oid": "61a73bf460a73d52d4566546"
    },
    "access_code": "7297230688",
    "session_users": [{
        "_id": {
            "$oid": "61a73bf460a73d52d4566545"
        },
        "last_active": {
            "$date": "2021-12-01T09:10:13.810Z"
        },
        "user_id": {
            "$oid": "61a722231970630db48cf518"
        },
        "user_status": "ACTIVE"
    }],
    "users": [{
        "$oid": "61a722231970630db48cf518"
    }],
    "__v": 0
}

I have tried these two solutions:

await session.session_users.pull({ session_users: { user_id: user._id }})
await session.session_users.pull({ user_id: user._id })

I use similar code to pull the user reference from the users array, which does work:

await session.users.pull(user)

I have also tried to get a session_user object as a reference similar to how user is, and use that to pull it from the array, but that doesn't work either. I have also tried to use findByIdAndUpdate with $pull using several different methods of trying to write the query.

To me it seems based on countless problems people have with the pull feature is that it is buggy, but I don't think I can get the item out of the array any other way. Any ideas?

CodePudding user response:

you have to do:

sessionModel.updateOne( { _id: YOUR_SESSION_ID }, { $pull: { session_users: { user_id: YOUR_USER_ID } } } )
  • Related