从mongodb对象数组中删除一个对象

时间:2019-08-06 12:36:41

标签: mongodb mongoose

我在删除猫鼬对象时遇到问题。 我有模式

shareholder.model.js

const Shareholder = mongoose.Schema({
    name: String,
    shares: [
        {
            type: mongoose.Schema.Types.Mixed, ref: 'shares' 
        }
    ],
})

mongoose.model('Shareholder', Shareholder)

所以我正在尝试从“共享”字段中删除对象

shareholder.service.js

// {shareholderId} id of object
// {shareId} unique id which have every object of the array

async function removeShareFromShareholder(shareholderId, shareId) {
try {
   await Shareholder.findByIdAndUpdate(shareholderId, 
                { $pull : { 'shares' : { '_id' : shareId } }},
                { safe: true })
    }
} catch (error) {
   throw new Error(`removeShareFromShareholder service error: ${error}`)
    }
}

但是上面的代码不起作用

能给我个建议吗

1 个答案:

答案 0 :(得分:1)

由于要保存ObjectId引用,因此应将shares的类型更改为Schema.Types.ObjectId

然后,因为该数组仅包含ids,而不包含具有_id属性更改的文档

{ $pull : { 'shares' : { '_id' : shareId } }}

{ $pull : { shares : shareId }}
相关问题