[英]Inability to pull from a nested array
I have this query我有这个查询
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});
}
});
I am just trying to remove an element from user object.我只是想从用户 object 中删除一个元素。 Here's the object这是 object
{
"_id": {
"$oid": "5ea2d8cffe35b93e84f7962b"
},
"pons": [
{
"$oid": "5ea98b181a2be04ec87aa710" // this is what I want to remove
}
],
"email": "test@test.tes",
"password": "$2a$12$VJ0MkcGUs42pikT42qLpyOb0Sd53j9LXH8dY9RdR/GcmUVzJoP8gi",
"__v": 0
}
This query doesn't throw any errors, catch doesn't catch anything, so I don't know what I'm doing wrong.这个查询没有抛出任何错误,catch 没有捕获任何东西,所以我不知道我做错了什么。 I tried just doing {pons: _id}
instead of {pons: {_id}}
but no luck.我试着只做{pons: _id}
而不是{pons: {_id}}
但没有运气。
The _id
is correct. _id
是正确的。 Checked with console.log.用 console.log 检查。
What am I missing?我错过了什么?
_id
is just a String
. _id
只是一个String
。 If you want to match an ObjectId
, you have to wrap it like this mongoose.Types.ObjectId(_id)
如果你想匹配一个ObjectId
,你必须像这样包装它mongoose.Types.ObjectId(_id)
const ObjectId = mongoose.Types.ObjectId
User.findOneAndUpdate(
{ _id: ObjectId(req.user._id) },
{ $pull: { pons: ObjectId(_id) } }
)
Since you are querying by _id
, you could also use User.findByIdAndUpdate()
which will wrap req.user._id
with ObjectId
for you.由于您通过_id
查询,您还可以使用User.findByIdAndUpdate()
它将req.user._id
与ObjectId
为您包装。
const ObjectId = mongoose.Types.ObjectId
User.findByIdAndUpdate(req.user._id, { $pull: { pons: ObjectId(_id) } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.