无法使用$ addToSet更新javascript对象字段

时间:2018-08-11 01:02:00

标签: javascript node.js mongodb

我有两个模型; UserLeague具有多对多关系,即用户可以是多个联赛的一部分,而联赛可以有多个用户。

var users = [
  {
    username: "user1@gmail.com",
    password: "password",
    userCreatedLeagues:[]
  },
  {
    username: "user2@hotmail.com",
    password: "password",
    userCreatedLeagues:[]
  },
  {
    username: "user3@gmail.com",
    password: "password",
    userCreatedLeagues:[]
  },
  {
    username: "user4@gmail.com",
    password: "password",
    userCreatedLeagues:[]
  }

]

var leagues = [
  {
    name: "League One",
    description: "Tournament One",
    tournament: "t1"
  },
  {
    name: "League Two",
    description: "Tournament Two",
    tournament: "t2"
  },
  {
    name: "League Three",
    description: "Tournament Three",
    tournament: "t3"
  },
  {
    name: "League Four",
    description: "Tournament Four",
    tournament: "t4"
  }
]

我当前正在编写一个seeds.js文件,该文件在启动我的应用程序时会上传虚拟数据。我可以成功将用户添加到League对象中,但是无法将联赛添加到userCreatedLeagues对象中的User数组字段中。

这是我的功能:

function addLeagues(){
    var user_counter = 0;
    leagues.forEach(function(newLeague, i){

      //find the user to link to the league
      setTimeout(function(){
        User.findOneAndUpdate(
          {user_id: user_counter + i},
          {$addToSet:{userCreatedLeagues: newLeague._id}}, function(err, user){
            if (user){
              console.log("counter is: ", user_counter + i);
              newLeague.owner = user;
              newLeague.members = [user.id];
              console.log("league added to user set: ", user);
            }
            console.log(err);
        });

        //create the league with all the relevant fields
        setTimeout(function(){
          League.create(newLeague, function(err, league){
            if(err){
              console.log(err);
            }
            league.save();
            console.log("added the league: " + league.name + " with ID: "
                        + league.id + "owned by : " + league.owner);
          });

        }, 2000);
      },1000);
    });

}

虽然User被链接到owner对象中的membersLeague字段,但行{$addToSet:{userCreatedLeagues: newLeague._id}}实际上并未将联赛添加到userCreatedLeagues字段。你能解释为什么会这样吗?

非常感谢您的帮助。

0 个答案:

没有答案