findByIdAndUpdate pull from array objects equal to a specific value

I want to remove one or more objects of type tweet from the timeline list within the user model. The tweet objects that I want to remove are those whose author id matches a specific id user._id.

I have tried this:

router.get("/follow/:userId", isLoggedIn, catchAsync(async (req, res) => {
    try {
        const currentUser = await User.findById(req.user._id).populate("timeline")
        const user = await User.findById(req.params.userId).populate("followers tweets")
        for (let tweet of currentUser.timeline) {
            if (tweet.author._id.equals(user._id)) {
                currentUser.timeline.pull(tweet._id)
            }
        }
        req.flash("error", `Unfollowed to ${user.username}`)
        user.save();
        currentUser.save()
        res.redirect(`/${user._id}`)
    } catch (err) {
        req.flash("error", err.message);
        res.redirect("back")
    }
}));

and this:

await User.findbyIdAndUpdate(currentuser._id, { $pull: { timeline: { author : user._id } } }

but none of them are working.

My user model:

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    biography: { type: String, maxlength: 160 },
    location: {type: String, maxlength: 30 },
    email: {
        type: String,
        unique: true,
        required: true
    },
    image: {
        url: String,
        filename: String,
    },
    followers: [{ type: Schema.Types.ObjectId, ref: "User" }],
    following: [{ type: Schema.Types.ObjectId, ref: "User" }],
    tweets: [{ type: Schema.Types.ObjectId, ref: "Tweet"}],
    timeline: [{ type: Schema.Types.ObjectId, ref: "Tweet"}]
});

My tweet model :

const tweetSchema = new Schema({
    images: [{ 
        url: String,
        filename : String
    }],
    text: { type: String, maxlength: 260},
    date: { type: Date, default: Date.now },
    author: { type: Schema.Types.ObjectId, ref: "User" },
    parent: { type: Schema.Types.ObjectId, ref: "Tweet", default:null },
    replies: [{ type: Schema.Types.ObjectId, ref: "Tweet" }],
    likes: [{ type: Schema.Types.ObjectId, ref: "User" }],
    retweets: [{ type: Schema.Types.ObjectId, ref: "Tweet" }],
    retweetStatus: {type: Schema.Types.ObjectId, ref: "Tweet", default: null}
});

28 thoughts on “findByIdAndUpdate pull from array objects equal to a specific value”

Leave a Comment