Search code examples
javascriptmongodbmongoosemongodb-querymongoose-schema

Delete object from array in mongoose


I have a mongoose Schmea, which looks like this: (Simplified)

const refreshSchema = new mongoose.Schema({
    token: String,
    expiration: Date
})

const userSchema = new mongoose.Schema({
    email: String,
    refreshTokens: [refreshSchema],
})

I have added some objects to the array refreshTokens, now I am trying to delete some of them

await User.update({email: this.email}, {$pull: { token }})
await User.updateOne({email: this.email}, {$pullAll: [{ token }]})

Neither works, the object still exists in refreshTokens. What am I doing wrong?


Solution

  • The form of $pull operator is:

    { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

    So your query should be:

    await User.update({email: this.email}, {$pull: { refreshTokens: { token } }})