2

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);
asked Sep 22, 2021 at 8:52
1
  • to get answer faster , if you can give sample data in and sample data out(the expected output that you want) Commented Sep 22, 2021 at 12:06

1 Answer 1

4

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)
})
answered Sep 22, 2021 at 14:31
Sign up to request clarification or add additional context in comments.

1 Comment

This worked thank you so much, very nice way of doing it

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.