我尝试了各种方法和方式来做到这一点,我正在尝试使用$pull方法
这是我的用户对象
我以前只有用户对象中的对象 ID,但现在我要删除完整的对象,我会搜索帖子的 ID,然后尝试将其取出
router.delete('/testing', (req, res, next) => {
postModel.findByIdAndRemove(req.query.postid, (error, returnedDocuments) => {
if (error) return next(error);
userModel.findOneAndUpdate(
// { email: req.query.email, posts: req.query.postid },
{ email: req.query.email },
{ $pull: { posts: { number: mongoose.Types.ObjectId(req.query.postid) } } },
{ new: true },
function(error, user) {
if (error) {
res.json(error);
}
console.log(`Post id ===== ${req.query.postid}`);
console.log(`Email===== ${req.query.email}`);
console.log(`returning user====${user}`);
res.json('Successfully updated user');
}
);
});
});
该帖子正在从帖子模型中删除,但我无法从用户发布的数组中删除该对象。
任何替代解决方案或关于为什么会发生这种情况的见解将不胜感激。
最佳答案
问题是 MongoDB 在比较值之前比较类型,并且没有应用隐式类型转换,因此而不是:
{ $pull: { posts: { number: req.query.postid } } }
你需要运行:
{ $pull: { posts: { number: mongoose.Types.ObjectId(req.query.postid) } } }
关于javascript - 无法使用 $pull (Mongoose) 删除用户模型数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867023/