0

This is my schema.

team_year: String,
team:  [{
    _leader: String,
    _member:[{
        _name: String, 
        _phone: String,
        _age: Number,
        _gender: String, 
        _comment:[{
            _date: String, 
            _contents: String,
            _attendance: Boolean
        }]
    }]
}]

I have data

{ team_year: 2015
    team: [
        {
          _leader: tom
          _member: [
              {_name: mike,
               _phone: 2222
          ]
        },
        {
          _leader:jack,
          _member: []
        }
    ]
}

I want to register a team member of Jack.

    team_schema.findOneAndUpdate(
        {team_year: '2015', 'team._leader' : 'jack'}, 

        {$push: {
                'team._member': req.body
            }
        },
        function(err, post){
        if (err) next(err);
        res.end("success");
    }); 

but it doesn't work. Please help me.

I use Node.js + express + MongoDB

I'm not good at English. T^T

LeeJaeng
  • 21
  • 4

1 Answers1

0

You need to specify the index of the object for which you want to insert an object (nested array). For this you can use the positional operator ('$') provided by MongoDB. See here for more info.

So this query should work:

team_schema.findOneAndUpdate(
    {team_year: '2015', 'team._leader' : 'jack'}, 

    {$push: {
            'team.$._member': req.body              //The $ symbol resolves to an index from the query
        }
    },
    function(err, post){
    if (err) next(err);
    res.end("success");
}); 
ZeMoon
  • 20,054
  • 5
  • 57
  • 98