Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

442
Views
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}
});
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

If your collection looks like this:

[
  {
    "_id" : ObjectId("60254276259a60228cbe5707"),
    "name" : "Mary",
    "timeline" : [
      ObjectId("60254276259a60228cbe5703"),
      ObjectId("60254276259a60228cbe5704"),
      ObjectId("60254276259a60228cbe5705")
    ]
  },
  {
    "_id" : ObjectId("60254276259a60228cbe5706"),
    "name" : "Dheemanth",
    "timeline" : [
      ObjectId("60254276259a60228cbe5700"),
      ObjectId("60254276259a60228cbe5701"),
      ObjectId("60254276259a60228cbe5702")
    ]
  }
]

then the solution is:

usersSchema.updateOne(
    {
        "_id": ObjectId("60254276259a60228cbe5706"),
        "timeline": ObjectId("60254276259a60228cbe5700"),
    },
    {
        $pull: {
            "timeline": ObjectId("60254276259a60228cbe5700")
        }
    }
)
.then()
.catch()

// or

usersSchema.findOneAndUpdate(
    {
        "_id": ObjectId("60254276259a60228cbe5706"),
        "timeline": ObjectId("60254276259a60228cbe5700"),
    },
    {
        $pull: {
            "timeline": ObjectId("60254276259a60228cbe5700")
        }
    },
    {
        new: true
    }
)
.then()
.catch()
over 4 years ago · Santiago Trujillo Report

0

I finally found the issue! The problem I was having is that I was trying to remove items from a list of objects while looping through that list. The solution is easy: you can just create an auxiliar empty array and push the items that you want to remove, then loop through that auxiliar array and pull the items from the original array.

In my case, I've already had an array with the tweets that I wanted to remove, user.tweets. The solution is:

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 user.tweets) {
            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")
    }
}));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!