Home > OS >  Mongoose update update nested object inside an array
Mongoose update update nested object inside an array

Time:09-23

I'm trying to query and update an element in the rosters array ( roster.schedule.monday.start) & then update the value in this example.

monday.start these two keys need to be dynamic

I think the approach would be something like this

  1. Find document by _id

  2. find matching object in array by _id

  3. update nested values

I have tried this below with no luck, could anybody assist in this problem

many thanks

// Mongoose query

exports.updateRoster = (req, res) => {

  const editDay = req.body.day;
  const value = req.body.valueOfEntry;
  const userId = req.body.id;
  const rosterId = req.body.rosterId;
  const startPerieod = req.body.time;


  let dynObj = {
    ["rosters.$.schedule.$."   editDay   ".$."   startPerieod]: value,
  };


  Carer.updateOne({ "rosters._id": rosterId }, { $set: dynObj }).exec(
    (err, roster) => {
      if (err) {
        return res.status(400).json({
          error: err,
        });
      }
      res.json(roster);
    }
  );
};


// Schema 

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const carersSchema = new mongoose.Schema({
 
  
  rosters: [
    {

   schedule: {

     monday: {

       start: { type: String },
       finish: { type: String },
       notes: { type: String },


    }, 
  ],

});

module.exports = mongoose.model("Carers", carersSchema);


CodePudding user response:

Try using $set and array filters like in the link

Carer.findOneAndUpdate({_id: carerId}, 
{ 
  "$set": {[`rosters.$[outer].schedule.${editDay}.${startPerieod}`]: value} 
},
{ 
  "arrayFilters": [{ "outer._id": roasterId }]
},
function(err, response) {
  if(err) console.log(err)
  console.log(response)
})
  • Related