我试图从子数组中删除一个对象,但没有运气,因为updateOne()不是函数,remove()不是函数。
我想删除id为'subcat 1'的'61cae5daf5bfbebd7cf748ef'对象
[
{
_id: '61cae5daf5bfbebd7cf748ee'
title: 'category 1',
SubCats: [
{
_id: '61cae5daf5bfbebd7cf748ef'
name: 'subcat 1',
image: '/assets/images/vr-box-6203301_1920.jpg',
},
{
_id: '61cae5daf5bfbebd7cf748fb'
name: 'subcat 2',
image: '/assets/images/galaxy-s20_highlights_kv_00.jpg',
},
]
},
]请帮帮忙
控制器
const deleteSubCategory = asyncHandler(async (req, res) => {
const subCategory = await Category.aggregate([
{ $unwind: "$SubCats" },
{ $replaceRoot: { newRoot: '$SubCats'} },
{ $match: { _id: ObjectId(req.params.id) }}
])
if (subCategory) {
await subCategory.updateOne({ $pull: {_id: ObjectId(req.params.id)}})
res.json({ message: 'sub-category removed' })
} else {
res.status(404)
throw new Error('sub-Category not found')
}
})发布于 2022-01-24 01:20:14
$update与$pull
db.collection.update({
"SubCats._id": "61cae5daf5bfbebd7cf748ef"
},
{
"$pull": {
SubCats: {
_id: "61cae5daf5bfbebd7cf748ef"
}
}
},
{
"multi": true
})https://stackoverflow.com/questions/70824182
复制相似问题