猫鼬 - 无法保存文档的属性

时间:2015-06-19 10:32:31

标签: node.js mongodb mongoose

所以我有用户和团队。我希望团队拥有一系列用户,并使用addUser函数将用户添加到团队中。我成功推送到团队用户阵列并保存结果,但在该功能之后,我打印出同一个团队,并且阵列中没有用户。我不确定这是否是.save()问题或者是什么。

感谢任何帮助,谢谢。

...

var userSchema = new Schema({
  name: { type: String, required: true, unique: true },
  age: Number
});
var teamSchema = new Schema({
  name: { type: String, required: true, unique: true },
  user: [{ type: Schema.ObjectId, ref: 'User' }]
});
userSchema.statics.createUser = function(opts, cb) {...};
teamSchema.statics.createTeam = function(opts, cb) {...};

teamSchema.statics.addUser = function(opts, cb) {
  Team.find({_id: opts.team}).exec( function (err, team) {
    team[0].user.push(opts.user);
    team[0].save(function(err, save) {
        console.log("--------------------");
        console.log(team[0]); //team contains the added user here
        console.log("--------------------");
        return cb(null);
    });
  });
};

var User = mongoose.model('User', userSchema);
var Team = mongoose.model('Team', teamSchema);   

var async = require('async');
var user1;
var user2;
var team;

async.waterfall([
  function(d){User.createUser({name :'test1'},function(err, user){
            user1 = user;
            d(err);
  });
  },

  function(d){User.createUser({name :'test2',age :20},function(err, user){
            user2 = user;
            d(err);
  });
  },

  function(d){Team.createTeam({name :'team'},function(err, obj){
            team = obj;
            d(err);
  });
  },
  function(d){Team.addUser({user : user1._id,team : team._id},   function(err){
            console.log(team);
            d(err);
  });
  },
  function(d){Team.addUser({user : user2._id,team : team._id},      function(err){
                console.log(team);
                d(err);
  });
  }

 ],function(err){
    if(err){
            console.log(err);
    }
    else{
      User.count({},function(err,count){console.log("Number of users:", count);});
      Team.count({},function(err,count){console.log("Number of teams:", count);});
      console.log(team);
    }

  });


returns:
--------------------
{ _id: 5583ed760958ab941a58bae9,
  name: 'team',
  __v: 1,
  user: [ 5583ed760958ab941a58bae7 ] } //user1 added
--------------------
{ __v: 0, name: 'team', _id: 5583ed760958ab941a58bae9, user: [] }
 //after that function call the team has no users
--------------------
{ _id: 5583ed760958ab941a58bae9,
  name: 'team',
  __v: 2,
  user: [ 5583ed760958ab941a58bae7, 5583ed760958ab941a58bae8 ] } 
//user2 added and user1 still there
--------------------
{ __v: 0, name: 'team', _id: 5583ed760958ab941a58bae9, user: [] } //no users again
Number of users: 2
Number of teams: 1 //only 1 team exists

1 个答案:

答案 0 :(得分:2)

也许尝试使用更新和推送,这也会简化您的代码?

findAndModify(mongodb命令)

findOneAndUpdate(mongoose命令)

Team.findOneAndUpdate({"_id" : opts.team} , {$addToSet : { "user" : opts.user}}, function (err, foundUpdatedTeam) {
  return cb(err,foundUpdatedTeam);
}, {new : true});

// be sure to update your team variable to reflect what is also in the database.

类似的东西:

function(d){Team.addUser({user : user1._id,team : team._id},   function(err, updatedTeam)        
{
  team = updatedTeam;
  console.log(team);
  d(err);
});

几个笔记:

  1. 我会将团队架构从用户更改为TeamUsers或更具描述性的东西......现在有点混乱。
  2. 请注意AddToSet的使用,以确保如果您已经添加了用户,则无法将他添加两次。
  3. 此代码更短更干净,如果您可以使用专用功能,则无需查找对象,但是如果您希望将用户添加到多个团队,我会使用允许您更新更新多个文件。