1

Is it possible to update a field using the value of another field?

Here is my schema

var timeSchema = new mongoose.Schema({
    hours: Number,
    minutes: Number
});

module.exports = mongoose.model("Time", timeSchema);

I want the value of minutes to be hours * 60 when minutes become 0

Here is my code

Time.updateMany({}, {minutes: hours * 60});

My code throws an error which says hours is not defined

Is there any possible way to update minutes using the value of hours?

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
Jerome Bravo
  • 583
  • 2
  • 5
  • 10

1 Answers1

2

Starting from MongoDB version 4.2, You can execute aggregation pipeline in updates i.e; you can utilize certain aggregation stages/operators in updates. So update part will be wrapped in [].

Try below query :

Time.updateMany({}, [{$set: {minutes: {$multiply : ['$hours', 60 ]}}}])

In the above query we've used $set alias $addFields stage of aggregation & $multiply aggregation operator to multiple existing hours field with 60 & store the value in minutes field.

Note : Just in case .updateMany() throws any error try the same with .update() with { multi : true } option.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46