Mongoose - 将对象推入嵌套数组

时间:2014-06-27 07:41:02

标签: node.js mongodb mongoose

我正在努力将学生对象推向学生的内心。团队对象的对象。以下是详细信息。

我从Niel那里得到了解决方案。最后注意到了。 Team.js

var TeamSchema = new Schema({
    // Team Name.
    name: String,
    lead: String,
    students :type: [{
      block : Number,
      status : String,
      student : {
        type: Schema.ObjectId,
        ref: 'Student'
    }]
});

Student.js

var StudentSchema = new Schema({
   name: String,
   rollNo : Number,
   class : Number
});

预期输出

team
{
    "__v": 1,
    "_id": "5252875356f64d6d28000001",
    "students": [
        {
            "__v": 1,
            "_id": "5252875a56f64d6d28000002",
             block : 1,
             status : invited,
            student: {
                "name": Sumeeth
                "rollNo" : 2
                "class" : 5
            }
        },
        {
            "__v": 1,
            "_id": "5252875a56f64d6d28000003",
            block : 1,
            status : invited,
            student: {
                "name": Sabari
                "rollNo" : 3
                "class" : 4
            }
        }
    ],
    "lead": "Ratha",   
}

当前输出

team

{
    "__v": 1,
    "_id": "5252875356f64d6d28000001",
    "students": [
        {
            "__v": 1,
            "_id": "5252875a56f64d6d28000002",
             block : 1,
             status : invited
        },
        {
            "__v": 1,
            "_id": "5252875a56f64d6d28000003",
            block : 1,
            status : invited
        }
    ],
    "lead": "Ratha",   
}

这是我用来在TeamAPI.js中使用Mongoose获取文档的JS

exports.students= {

    /*
     * ### Create Player
     */
 create: function(req, res) {
 var _team = req.team;
        var student = req.body;
        var _student = new Student(student);
            Student.create(student);
            _team.update({
                $push: {
                    students: {
                        student: new Student(student),
                        block : ‘1’,
                        status: 'invited'
                    }
                }
            });
}
}

解决方案

var _student = new Student(student);                        
            _student.save();
            _team.update({
                $push: {
                    students: {
                        student: _student,
                        invite: _invite,
                        status: 'invited'
                    }
                }
            }

有人请在我错的地方帮助我。我应该如何利用推送,以便我可以在团队内部获得学生对象。

0 个答案:

没有答案