Search code examples
javascriptnode.jsmongodbmongoosechat

Mongoose - Remove an object from array of messages


I need to remove a message from array of messages in mongoose..How can I do this? My Schema :

const ChatMessages = new Schema({
    room: {
        type: Schema.Types.Mixed,
        required: true
    },
    messages: [{
        sender: {
            type: String,
            required: true
        },
        text: {
            type: String,
            required: true
        },
        display: {
            type: String,
            required: true
        },
        date: {
            type: Date,
            default: Date.now,
        }

    }]
})

My code is :

await ChatMessages.updateOne({ room },{ $pull: { messages: { _id: new ObjectId(_id) } }}, { multi: true})

Document Example

id: ObjetId(6051f0bbe23bf3129b8f8eb6)
room:"111"
__v:0
messages: Array

Solution

  • I reproduced the issue with my example document here:

    {
        "_id": ObjectId("604bacf4dfe5ed598c350737")
        "array": [
            {
                "_id": ObjectId("60474814a380df6aade743cd"),
                "value": NumberInt(785)
            }
        ]
    }
    

    If I go with updateOne() and multi options, it throws an error. So I executed it with update() and multi:

    db.documents.update({ _id: ObjectId("604bacf4dfe5ed598c350737") }, {
        $pull: {
            array: {
                _id: ObjectId("60474814a380df6aade743cd")
            }
        }
    }, { multi: true })
    

    This is the result document:

    {
        "_id": ObjectId("604bacf4dfe5ed598c350737")
        "array": []
    }
    

    So in your case, keeping the new ObjectId(_id) and using update() should solve the problem. If there is still a problem with the $pull, it means there is an issue with the find query: { room }.

    For more info: https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents