Mongoose $pull操作符未能从数组中删除ObjectID

3
在我的应用程序中,我有一个帖子模式(如下所示):
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
    }]
})

当用户发送请求时,我想从喜欢的数组中删除一个objectid

路由:

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')

然而,当调用路由时,objectid并未从数组中移除。有人能找出原因吗?谢谢。
更新:
const user = mongoose.Types.ObjectId(req.user._id)

更新 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)_id 转换为对象 ID。 - turivishal
@turivishal 你好。这个代码仍然没有从likes数组中删除对象ID。请参见上面的更新代码。 - NodeReact020
你正在对查找到的对象执行更新操作,只需执行单独的查询 await Post.update({}, { $pull: { likes: mongoose.Types.ObjectId(req.user._id) } }) - turivishal
@turivishal 你好,这还没有起作用。请检查上面更新的代码。 - NodeReact020
1
在查询之前加上 await,不需要使用 post.save() 命令,因为 updateOne 将保存事务,如果仍然无法正常工作,则尝试转换查询 {_id: mongoose.Types.ObjectId(req.params.postid)} - turivishal
1个回答

5

您可以在一个查询中执行两个操作,无需使用findOne

  • 使用mongoose.Types.ObjectIdreq.user._id转换为对象ID
  • $inc来减少likeNum的计数
await Post.updateOne(
  { _id:  req.params.postid },
  {
    $pull: { likes: mongoose.Types.ObjectId(req.user._id) },
    $inc: { likeNum: -1 }
  }
);
res.send('Unliked');

游乐场


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接