使用Mongoose

时间:2015-09-01 18:27:04

标签: node.js mongodb mongoose

我的宗族计划中有以下内容

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}
      }
    ],

如何从部落中删除用户?我尝试了一些方法,看起来像最少的代码:

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

似乎运行,但用户坚持使用文档..

家族

{ _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 } ] }

用户

{ _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 个答案:

答案 0 :(得分:1)

使用过滤功能并保存。

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

clan.markModified('members');
clan.save(function(err)