无法从嵌套数组中提取



我有这个查询

router.delete('/:_id', async (req, res) => {
const {_id} = req.params;
const errors = [];
console.log(_id);
await Promise.all([
// Pon.findOneAndDelete({_id}).catch((e) => {
//   console.log(e);
//   errors.push('Something went wrong. Pon was not deleted');
// }),
// ^^^^^^^^^ this part worked. Wanted to just test the other query
User.findOneAndUpdate({_id: req.user._id}, {$pull: {pons: {_id}}}).catch((e) => {
console.log(1, e);
errors.push('Something went wrong. Pon reference was not deleted from user');
}),
]);
if (errors.length > 0) {
console.log(2, errors);
res.json({ok: false, errors});
} else {
res.json({ok: true});
}
});

我只是想从用户对象中删除一个元素。这是目标

{
"_id": {
"$oid": "5ea2d8cffe35b93e84f7962b"
},
"pons": [
{
"$oid": "5ea98b181a2be04ec87aa710" // this is what I want to remove
}
],
"email": "test@test.tes",
"password": "$2a$12$VJ0MkcGUs42pikT42qLpyOb0Sd53j9LXH8dY9RdR/GcmUVzJoP8gi",
"__v": 0
}

这个查询没有抛出任何错误,catch也没有捕获任何内容,所以我不知道我做错了什么。我试着只做{pons: _id}而不是{pons: {_id}},但没有成功。

_id正确。已通过console.log 进行检查

我错过了什么?

_id只是一个String。如果你想匹配一个ObjectId,你必须像这个mongoose.Types.ObjectId(_id)一样包装它

const ObjectId = mongoose.Types.ObjectId
User.findOneAndUpdate(
{ _id: ObjectId(req.user._id) },
{ $pull: { pons: ObjectId(_id) } }
)

由于您是通过_id进行查询的,您也可以使用User.findByIdAndUpdate(),它将为您用ObjectId包装req.user._id

const ObjectId = mongoose.Types.ObjectId
User.findByIdAndUpdate(req.user._id, { $pull: { pons: ObjectId(_id) } })

最新更新