0

I have the following in my clan scheme

var ClanScheme = new mongoose.Schema
({
    name: {type: String, unique: true},
    members: 
    [
      {
        user: {type: mongoose.Schema.Types.ObjectId, ref:'User', unique: true},
        wins: {type: Number, default: 0},
        losses: {type: Number, default: 0}
      }
    ],

How do I remove a user from the clan? I've tried a few methods this looking like the least code:

clan.members.remove({'user':userObj._id});
clan.save(function(err)

It seems to run, but the user sticks in the document..

Clan

{ _id: 55e5e8d017e055495dcc3643,
  name: 'DBz',
  __v: 9,
  rating: 1000,
  losses: 0,
  wins: 0,
  rank: 0,
  members: 
   [ { user: [Object], 
       _id: 55e5e8d017e055495dcc3644,
       losses: 0,
       wins: 0 },
     { user: [Object],
       _id: 55e5eb0f17e055495dcc3645, //<< 55e4ac0340f964d52f8e7fb7
       losses: 0,
       wins: 0 } ] }

User

{ _id: 55e4ac0340f964d52f8e7fb7,
  facebookid: '999',
  name: 'Joe Blogs',
  __v: 0,
  lastDevice: { device: 'Desktop', id: 'adsbr2fjui33emk9p6gtnfrulv' },
  multiplayer: 
   { clanid: 55e5e8d017e055495dcc3643,
     powers: [],
     world_commander: 0,
     losses: 0,
     wins: 0,
     clanname: 'DBz',
     rating: 1000,
     rank: 0,
     username: 'Joe' },
  saveDataSeed: 40wq211,
  saveData: 'yuV2hVJA00zYGm'}

1 Answer 1

1

Use a filter function and save.

clan.members = clan.members.filter(function(member){
  return String(member.user._id) !== String(userObj._id);
});

clan.markModified('members');
clan.save(function(err)
Sign up to request clarification or add additional context in comments.

6 Comments

This doesn't work, the user still sticks in the clan.
No error at all, it runs and say it's done but it doesn't really delete.
Post the result of console.log(clan) and console.log(userObj)
I've edited my answer as well, please add the markModified call
Oh, I see, that's because member.user is an object. In your console output, I cant see inside of it as its masked as [Object], but what you essentially want is to compare the _id's. I'm guessing it should be String(member.user._id). You'll still want the mark modified call. I've edited my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.