Mongoose deleting (pull) a document within an array, does not work with ObjectID

后端 未结 7 1552
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 16:35

I have the following mongoose schema:

user = {
    \"userId\" : \"myId\",
    \"connections\":
    [{
        \"dateConnectedUnix\": 1334567891,
        \"is         


        
7条回答
  •  盖世英雄少女心
    2020-11-27 17:17

    In mongoose 5.8.11, this $pull: { ... } didn't work for me, so far not sure why. So I overcame it in my controller this way:

    exports.removePost = async (req, res, next) => {
      const postId = req.params.postId;
      try {
        const foundPost = await Post.findById(postId);
        const foundUser = await User.findById(req.userId);
        if (!foundPost || !foundUser) {
          const err = new Error(
            'Could not find post / user.',
          );
          err.statusCode = 404;
          throw err;
        }
        // delete post from posts collection:
        await Post.findByIdAndRemove(postId);
        // also delete that post from posts array of id's in user's collection:
        foundUser.posts.pull({ _id: postId });
        await foundUser.save();
        res.status(200).json({ message: 'Deleted post.' });
      } catch (err) {
        // ...
      }
    };
    

提交回复
热议问题