我有两个模型; User
和League
具有多对多关系,即用户可以是多个联赛的一部分,而联赛可以有多个用户。
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
对象中的members
和League
字段,但行{$addToSet:{userCreatedLeagues: newLeague._id}}
实际上并未将联赛添加到userCreatedLeagues
字段。你能解释为什么会这样吗?
非常感谢您的帮助。