我确定我的语法不正确,因此请查看是否可以帮助我从数组中删除项目:
BaseUser.findOneAndDelete({
baseId: req.body.baseId,
userId: { $eq: req.body.username }
})
.then(user => {
console.log(`Deleted base with ID \`${req.body.id}\``);
res.status(204);
return user;
})
.then(user => {
Base.findById(user.baseId)
.then(base => {
base.update({}, { $pull: { users: user._id } });
return base.save();
})
.then(result => console.log(result));
})
base
如下所示:
{ created: 2018-09-05T19:28:06.947Z,
users: [ 5b902e5448872a1da8b20536, 5b902f079f67030598f5dec0 ],
messages: [],
_id: 5b902e5448872a1da8b20535,
creatorId: 5b7ee54ceb5ab41db89e04c3,
title: 'testBase1',
__v: 4 }
user._id
等于5b902f079f67030598f5dec0
。我忘记了某事
答案 0 :(得分:0)
答案:
Base.findById(user.baseId)
.then(base => {
let indexOf = base.users.indexOf(user._id);
base.users.splice(indexOf, 1);
return base.save();
})
$pull
等mongo方法对我不起作用。相反,我在数组中找到了已删除的_id
的索引,并使用splice
答案 1 :(得分:0)
尝试添加{ new: true }
BaseUser.findOneAndDelete({
baseId: req.body.baseId,
userId: { $eq: req.body.username }
})
.then(user => {
console.log(`Deleted base with ID \`${req.body.id}\``);
res.status(204);
return user;
})
.then(user => {
Base.findById(user.baseId)
.then(base => {
base.update({}, { $pull: { users: user._id } }, { new: true });
return base.save();
})
.then(result => console.log(result));
});