简体   繁体   中英

Mongoose deleteing subdocuments $push

I'm having problems deleting subdocuments using mongoose.

I have a schema set up like this:

let baseSchema = new mongoose.Schema({
    basename: String,   
    admins: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }]
})

the Base.admins is populated by an array of users who have admin authority. I want to be able to remove users from that array. the below code is getting the data from Mongo but not removing the user with that id, it is returning the same data as before the update/pull request.

await Base.findOneAndUpdate({ _id: baseId }, {$pull: {admins: { _id: userId }}}, { new: true });

I have made sure that userId is an object type using

userId = mongoose.mongo.ObjectID(userId );

does anyone have any suggestions about how to delete a user from the admin array and then save the document to the db?

Not sure why but when I used $pullAll instead of $pull it worked. ie

await Base.findByIdAndUpdate(baseId, { $pullAll: { admins: [userId] } }, { new: true });

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