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

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

I have the following mongoose schema:

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


        
相关标签:
7条回答
  • 2020-11-27 17:02
    user: {
     _id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
     name: 'Test',
     posts: [
      ObjectId("5cd07ee05c08f51af8d23b64"),
      ObjectId("5cd07ee05c08f51af8d23c52")
     ]
    }
    

    Remove a single post from posts array

    user.posts.pull("5cd07ee05c08f51af8d23b64"); user.save();

    0 讨论(0)
  • 2020-11-27 17:04

    mongoose: 4.11.11
    What have worked for me is the following syntax:

    const removeTansactionFromUser = (userId, connectionId) => {
        return User.findByIdAndUpdate(userId, { $pull: { "connections": connectionId} }, {'new': true} );
    };
    

    Mongoose support id in string format or ObjectId format.
    Tip: new ObjectId(stringId) to switch from string to ObjectId

    0 讨论(0)
  • 2020-11-27 17:10

    I have a document like

    I have to delete address from address array

    After searching lots on internet I found the solution

     Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, function(err, data){
            if(err) {
              return res.status(500).json({'error' : 'error in deleting address'});
            }
    
            res.json(data);
    
          });
    
    0 讨论(0)
  • 2020-11-27 17:15

    It seems that the above code would not work. It should not even have worked for the first example I gave.

    In the end I was supported by this answer here: MongoDB, remove object from array

    Here is my working code:

    userAccounts.update( 
          { userId: usr.userId },
          { $pull: { connections : { _id : connId } } },
          { safe: true },
          function removeConnectionsCB(err, obj) {
              ...
          });
    
    0 讨论(0)
  • 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) {
        // ...
      }
    };
    
    0 讨论(0)
  • 2020-11-27 17:18

    To use update with ObjectId, you should use ObjectId object instead of string representation :

    var ObjectId = require('mongoose').Types.ObjectId;
    
    userAccounts.update({'connections._id': new ObjectId('1234-someId-6789') }, 
                    {$pull: { 'connections._id': new ObjectId('1234-someId-6789') }}, 
                    function (err,val) {
                        console.log(val)
                    });
    
    0 讨论(0)
提交回复
热议问题