$ pull不从集合中删除元素(mongodb)

时间:2019-06-27 08:46:51

标签: node.js mongodb mongoose

我正在尝试建立一个类似/不同的系统。和不一样,我需要从喜欢阵列中删除用户。但是mongodb $pull不起作用。 $inc命令工作正常,但$pull无效。

这是我的模式

    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: "User"
    },
    likes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        }
    ],
    likeCount: {
        type: Number,
        default: 0
    },
    commentBody: {
        type: String
    },
    contentId: {
        type: mongoose.Schema.Types.ObjectId,
        refPath: "contentType",
        required: true
    },
    contentType: {
        type: String,
        required: true,
        enum: ["Video", "Comment"]
    },
    isApproved: {
        type: Boolean,
        default: true
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Comment"
        }
    ],
    postedOn: {
        type: Date,
        default: Date.now()
    }

mongodb查询

await Video.updateOne(
                { _id: contentId, likeCount: { $gt: 0 } },
                {
                    $pull: {
                        likes: decoded.id
                    },
                    $inc: { likeCount: -1 }
                }
            );

1 个答案:

答案 0 :(得分:0)

您应该将查询更新为如下形式:

await Video.updateOne(
                { _id: contentId, likeCount: { $gt: 0 } },
                {
                    $pull: {
                        "likes": { "_id": ObjectId(decoded.id)}
                    },
                    $inc: { likeCount: -1 }
                }
            );

我假设在devede.id中有字符串,并且string与ObjectId不同。因此,我们需要将其转换为ObjectId

相关问题