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')
mongoose.Types.ObjectId(req.user._id)await Post.update({}, { $pull: { likes: mongoose.Types.ObjectId(req.user._id) } })awaitbefore query and no need topost.save()command becauseupdateOnewill save transaction, and if it still not work then try to convert your query{_id: mongoose.Types.ObjectId(req.params.postid)}