Mongoose, pull from subdocument

后端 未结 2 1254
囚心锁ツ
囚心锁ツ 2021-01-14 19:21

This is my document:

{ 
  password: \'87654321\',
  title: \'Organization A\',
  members: 
   [ { tier: 1,
       joinedDate: Sun May 12 2013 00:00:00 GMT+02         


        
相关标签:
2条回答
  • 2021-01-14 19:50

    It appears that the MongooseArray#pull method only works if your elements have _id properties.

    I find it easier to use direct calls to update to avoid these sorts of surprises:

    mongoose.model('organization').update(
        {_id: user.organization},
        {$pull: {members: {user: user._id}}},
        function(err, numAffected) { ... }
    );
    
    0 讨论(0)
  • 2021-01-14 20:11

    I don't see any id referenced in your members array, remove _id and do it directly to your user property since that's what is on the schema.

    mongoose.model('organization').findOne({_id:user.organization}, function(err, org){
          org.members.pull({'user':user._id});
          org.save();
        })
    

    EDIT: maybe this one

    mongoose.model('organization').update({ _id: user.organization }, {$pull: 
    {members.user: user._id}}, {}, function(err, numAffected){
     //check numAffected
    
    });
    

    try that out!

    0 讨论(0)
提交回复
热议问题