通过Express.JS Router将数据添加到Mongo Array

时间:2019-05-09 14:19:57

标签: node.js mongodb express mongoose

我想将请求参数中的数据添加到MongoDb数组中。我的架构看起来像这样

var studentSchema = mongoose.Schema({
    first_name: {type: String},
    roll_num: {type: String},
    experiences: [{
        experienceTitle: String,
        Employer: String,
        fromYear: Number,
        toYear: Number
    }]
});

到目前为止,我已经可以通过看起来像这样的简单快速路由器将数据添加到first_nameroll_num

router.post('/createStudent',(req, res, next) => {
    var newStudent = new student({
        first_name: req.body.first_name,
        roll_num: req.body.roll_num,
    });
    newStudent.save((err, student) => {
        if(err){
            res.status(500).json({errmsg: err});
        }
        else{
            res.status(200).json({msg: student});
        }
    })
});

我想将数据添加到experiences数组中。我已经编写了一些函数来实现此目的,但到目前为止,我只能用空的experiences数组来创建学生。

1 个答案:

答案 0 :(得分:0)

您尝试过吗:


//...

const student = new Student({
    first_name: "testFirstName",
    roll_num: "R0000",
    experiences: [{
        experienceName: "testExp1",
        experienceEmployer: "testEmpl",
        fromYear: 1994,
        toYear: 1995
    }, {
        experienceName: "testExp2",
        experienceEmployer: "testEmp3",
        fromYear: 1996,
        toYear: 1997
    }]
});

await student.save();

//...