Home > Software engineering >  updatemany by taking existing field value and and new field in moongoose
updatemany by taking existing field value and and new field in moongoose

Time:09-28

this is my schema

const winSchema = new mongoose.Schema( {
    windo_no:Number,

  
    time:{
        start_time:  {hours: {
            type: Number, min: 0, max: 23
          },
         minutes: {
            type: Number,  min: 0, max: 59
          }
         },

        current_time:  {hours: {
            type: Number,  min: 0, max: 23
        },
        minutes: {
            type: Number,  min: 0, max: 59
        }},
        
        end_time:  {hours: {
            type: Number,  min: 0, max: 23
        },
        minutes: {
            type: Number,  min: 0, max: 59
        }},
   
    },

    date:[{
        date:String ,
        holiday:Boolean,
        allocation:[{
            tokenid:Number,
            compelte:{
                type: Boolean,
                default: false
            },
            m_number:Number,
            services_id:Number,
            allocated_time:{hours: {
                type: Number,  min: 0, max: 23
            },
            minutes: {
                type: Number, min: 0, max: 59
            }},

        }]
    




    }]

});

module.exports = mongoose.model('Window', winSchema)

I will run query every day in which I want to update for all windows current_time will be equal to start_time at single time trying to do updatemany() but how to get and set value from already inserted field value

 // set current_time=starttime
 router.post("/settime", async (req, res) => {


  let result = await model.updateMany({ },
   {
   $push: {time:{ current_time: {hours:11}} },
  },

)}); here I despite of writing hours:11 I want to add start_time hours field value

 let result2 =   await model.updateMany({},{
 $push: 
   // {'time.current_time': 'time.start_time'}
     {time:{ current_time: "$start_time"} },
   })

CodePudding user response:

Try using $expr:

router.post('/settime', async (req, res) => {
  let result = await model.updateMany(
    { $expr: { $eq: [ '$start_time', '$current_time' ] } },
    {
      $push: { time: { current_time: { hours: 11 } } },
    }
  );
});

CodePudding user response:

 let result2 =   await model.updateMany({},
 [{$set:{"time.current_time":"$time.start_time"}}])
  • Related