简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM