首页 > 解决方案 > 如何删除 MongoDB 中的 ObjectID 数组?

问题描述

我有两个集合,露营地和评论,同时删除评论时它作为 ObjectID 参考保留在露营地的对象数组中,我找不到从那里删除它们的方法。

我试过了

db.campgrounds.update({ title: "Ancient Hunting Camp" }, { $pull:{id:"60f8293044b0cc40c409f2f7"}})
db.campgrounds.update({ title: "Ancient Hunting Camp" }, { $pull: {reviews:{id:"60f8293044b0cc40c409f2f7"}}})
db.campgrounds.update({ title: "Ancient Hunting Camp" }, { $pullAll: {reviews:[]}},{multi:true})
db.campgrounds.update({ title: "Ancient Hunting Camp" }, { $pull: { reviews: {}}}, {multi:true})
db.campgrounds.update({ _id: "603d7a10f969af31484fb56e" }, { $pull: { reviews: "ratings"}})
db.campgrounds.update({ _id: "603d7a10f969af31484fb56e" }, { $pull: { reviews: ObjectId("60f976cd6132a91a20bd6679") }}

我有这些结果

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

或者

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

或者

WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 2,
"errmsg" : "Cannot apply $pull to a non-array value"
}
})`

露营地架构

    const CampgroundSchema = new Schema({

    title: String,
    image: String,
    price: Number,
    description: String,
    location: String,
    tel: Number,
    website: String,
    email: String,

    reviews: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Review'
        }
    ]
})

标签: node.jsmongodb

解决方案


推荐阅读