MongoDB JS Script只运行单循环

时间:2016-08-11 18:26:44

标签: javascript mongodb

我使用以下脚本在我的数据库中生成测试对象。

var numberOfTeams = 3;
var membersPerTeam = 1;

function generateMembers() {
    var arr = [];
    for (i =0 ;i < membersPerTeam; i++) {
        var randomNumber = Math.floor((Math.random() * 10) + 1).toString();
        var isAdmin = false;
        if (i ==0 ) {
            isAdmin = true;
        }
        arr.push({
            "memberId": randomNumber,
            "admin": isAdmin,
            "name": "member" + randomNumber ,
            "email" : "member" + randomNumber + "@test.com"
        });
    }
    return arr
}

for (var i =0; i<numberOfTeams; i++) {
    db.team.insert({
        "teamName": "test-team-generated" + i,
        "members": generateMembers(),
        "credits" : NumberInt(5000),
        "maxTeamSize": NumberInt(membersPerTeam)
    })
}

问题是在单个循环之后,脚本将退出。我正在寻找一种方法来设置作为Int&#39; s插入的所有值,并且只要将numberOfTeams值设置为,就使循环运行。

1 个答案:

答案 0 :(得分:1)

你的代码中有一个嵌套循环,它不应该存在,因为在循环中你调用的函数generateMembers()有另一个循环。 您需要以运行插入操作之前填充变量的方式分隔调用。您也可以通过一次操作插入一组文档。

以下示例重构代码:

function generateMembers(membersPerTeam) {
    var arr = [];
    for (i =0 ;i < membersPerTeam; i++) {
        var randomNumber = Math.floor((Math.random() * 10) + 1).toString();
        var isAdmin = false;
        if (i ==0 ) {
            isAdmin = true;
        }
        arr.push({
            "memberId": randomNumber,
            "admin": isAdmin,
            "name": "member" + randomNumber ,
            "email" : "member" + randomNumber + "@test.com"
        });
    }
    return arr
}

var docs = [],
    membersPerTeam = 3,
    members = generateMembers(membersPerTeam);

for (var i =0; i<numberOfTeams; i++) {
    docs.push({
        "teamName": "test-team-generated" + i,
        "members": members,
        "credits" : NumberInt(5000),
        "maxTeamSize": NumberInt(membersPerTeam)
    });
}

db.team.insert(docs)