mongo $ pull不会删除字符串

时间:2018-09-05 19:45:16

标签: node.js mongodb mongoose

我确定我的语法不正确,因此请查看是否可以帮助我从数组中删除项目:

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。我忘记了某事

2 个答案:

答案 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

的原始JS方法删除了该条目。

答案 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));
    });