0

I have a problem with removing an object in mongoose. I have the schema

shareholder.model.js

const Shareholder = mongoose.Schema({
    name: String,
    shares: [
        {
            type: mongoose.Schema.Types.Mixed, ref: 'shares' 
        }
    ],
})

mongoose.model('Shareholder', Shareholder)

So I'm trying to remove an object from 'shares' field

shareholder.service.js

// {shareholderId} id of object
// {shareId} unique id which have every object of the array

async function removeShareFromShareholder(shareholderId, shareId) {
try {
   await Shareholder.findByIdAndUpdate(shareholderId, 
                { $pull : { 'shares' : { '_id' : shareId } }},
                { safe: true })
    }
} catch (error) {
   throw new Error(`removeShareFromShareholder service error: ${error}`)
    }
}

But code above doesn't work

Can you give me an advice

1 Answer 1

1

Since you are saving ObjectId refs, you should change the type of shares to Schema.Types.ObjectId

then since the array contains only ids and not a document with the _id property change

{ $pull : { 'shares' : { '_id' : shareId } }}

to

{ $pull : { shares : shareId }}
Sign up to request clarification or add additional context in comments.

1 Comment

You're awesome! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.