简体   繁体   中英

Variables inside $push not working in Mongoose

I have this Schema

courses: [],
workshops: [],
events: [],
semesters: {
  sem1: { cie1: [], cie2: [], cie3: [], final: [] },
  sem2: { cie1: [], cie2: [], cie3: [], final: [] },
  sem3: { cie1: [], cie2: [], cie3: [], final: [] },
  sem4: { cie1: [], cie2: [], cie3: [], final: [] },
  sem5: { cie1: [], cie2: [], cie3: [], final: [] },
  sem6: { cie1: [], cie2: [], cie3: [], final: [] },
  sem7: { cie1: [], cie2: [], cie3: [], final: [] },
  sem8: { cie1: [], cie2: [], cie3: [], final: [] },
},

I want push data in CIE's and Final Array of each sem I use this to do

  if(type==="cie"){
    const path = "semesters.sem"+semester+".cie"+num;
    // const path = "semesters.sem1.final.";
    Student.update({reg_no: req.body.regno},{$push:{path:req.body.submarks}},function(err,result){
        res.send(err);
    });
  }
  if(type === "final"){
    // const path = "semesters.sem"+semester+".final";
    const path = "semesters.sem1.final.";
    Student.update({reg_no: req.body.regno},{$push:{path:req.body.submarks}},function(err,result){
      res.send(result);
  });
  }

I use path variable to define the path but it's not working when I give path as String in push it works but this does not works when I give as string variable. Help Me Resolving this.

To use varibale as object key, you need to do something like:

{ $push: { [path]: req.body.submarks } }

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