3

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')
5
  • try converting _id to object id using mongoose.Types.ObjectId(req.user._id) Commented Feb 7, 2021 at 16:57
  • @turivishal Hello. This still has not removed the object id from the likes array. See update code above. Commented Feb 7, 2021 at 17:00
  • you are doing update operation on find object, just do separate query await Post.update({}, { $pull: { likes: mongoose.Types.ObjectId(req.user._id) } }) Commented Feb 7, 2021 at 17:02
  • @turivishal Hi this has still not worked. Please check updated code above Commented Feb 7, 2021 at 17:05
  • 1
    put await before query and no need to post.save() command because updateOne will save transaction, and if it still not work then try to convert your query {_id: mongoose.Types.ObjectId(req.params.postid)} Commented Feb 7, 2021 at 17:08

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.