Search code examples
javascriptnode.jsmongoosemongoose-schema

Mongoose $pull operator not removing ObjectID from array


In my application, I have a post schema (shown below):

const postSchema = new mongoose.Schema({
    file: {
        type: String,
        required: true
    },
    caption: {
        type: String,
        maxLength: 2000 
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    likeNum: {
        type: Number,
        default: 0,
        min: 0
    },
    likes: [{
        type: mongoose.Schema.Types.ObjectId
    }]
})

I want to remove an objectid from the likes array when a user request is sent.

Route:

const post = await Post.findOne({_id: req.params.postid})
const user = req.user._id

post.update({}, {$pull: {likes: user}})
post.likeNum--
await post.save()
res.send('Unliked')

However the objectid is not removed from the array when the route is called. Can anyone spot why? Thanks.

UPDATE:

const user = mongoose.Types.ObjectId(req.user._id)

UPDATE 2:

Post.updateOne({_id: req.params.postid}, { $pull: { likes: mongoose.Types.ObjectId(req.user._id) } })
post.likeNum--
await post.save()
res.send('Unliked')

Solution

  • You can do both operations in a single query no need to findOne,

    • convert req.user._id to object id using mongoose.Types.ObjectId
    • $inc to decrees the counts of likeNum
    await Post.updateOne(
      { _id:  req.params.postid },
      {
        $pull: { likes: mongoose.Types.ObjectId(req.user._id) },
        $inc: { likeNum: -1 }
      }
    );
    res.send('Unliked');
    

    Playground