mongoose:将数据插入嵌套对象数组中

时间:2015-10-07 15:08:43

标签: javascript node.js mongodb express mongoose

我正在使用node.js mongodb开发一个项目。我的架构有点像:

var Doctor = new Schema({
    email : String,
    password : String,
    Dname : String,
    blockAppoint:[{
        day:String,
        sslot:[Number],
        eslot:[Number],
        address:String,
        status1:String
    }]
});

如果我将所有这些值作为用户的输入,我无法弄清楚如何插入到嵌套对象的数组中。 如果我的帖子api看起来像:

var doc = new Doctor({
                email : req.body.email,
                password : req.body.password,
                name : req.body.Dname,
                blockAppoint:{
                              status1:req.body.xx,
                              day:req.body.day,
                              sslot:req.body.sslot,
                              eslot:req.body.eslot,
                              address:req.body.address
                            }
                });
doc.save(function(err){
                if(err){
                    res.send(err);
                    return;
                }
                res.json({
                    success: true,
                    message: 'doctor has been added!'   
                });
            });     

我只能在数据库中输入一个条目。有谁知道如何更改我的api代码,以便能够将读取输入到我的数据库中。

1 个答案:

答案 0 :(得分:1)

首先尝试使用 push() 方法将值添加到数组中:

var sslot = [], eslot = [], blockAppoint = [];
sslot.push(req.body.sslot);
eslot.push(req.body.eslot);
blockAppoint.push({
    status1: req.body.xx,
    day: req.body.day,
    sslot: sslot,
    eslot: eslot,
    address: req.body.address
});

var doc = new Doctor({
    email: req.body.email,
    password: req.body.password,
    name: req.body.Dname,
    blockAppoint: blockAppoint
});