Home > Enterprise >  Delete object from array in mongoose
Delete object from array in mongoose

Time:11-13

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?

CodePudding user response:

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 } }})
  • Related