简体   繁体   中英

mongoose : insert data into an array of nested objects

I am working on a project using node.js mongodb. My schema somewhat looks like:

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

If I take all these values as input from user, I can't figure out how to insert into the array of nested objects. If my post api looks like:

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!'   
                });
            });     

I'm able to input just one entry into the database. Does anyone know how do I change my api code so as to be able to take read input into my database.

Try adding the values to an array first using the push() method:

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM