I
I
Ilya Kolesnikov2018-11-11 17:21:52
MongoDB
Ilya Kolesnikov, 2018-11-11 17:21:52

How to change the property of the model you refer to?

Hello. I am writing an application that has workouts consisting of exercises. I create models like this:

const valuesOfExercise = new Schema({
  exercise: {type: Schema.Types.ObjectId, ref: "Exercise"},
  repeats: {type: Number, required: true},
  measure: {type: Number, required: true},
  order: {type: Number}
})

const workoutSchema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: "User" },
  date: {type: Date},
  exercises: [valuesOfExercise]
})

At the front, it is possible to remove an exercise from a workout or rearrange the exercises.
Accordingly, the order value, by which the exercises are sorted, is responsible for the order in which the exercises are performed. After removing each exercise, a hole is formed that needs to be closed. An object comes from the front, which is to be removed. The code looks like this:
const {itemToDelete} = req.body
Workout.find({user: req.payload._id}).populate({path: 'exercises.exercise'})
      .exec((err, item)=>{
        item.map((ex, i)=>{
          let arr = [...ex.exercises]
          arr.splice(itemToDelete.order, 1)
          arr.map((ex, index)=>{
            ex.order = index;
            
          })
          console.log(arr)
        })
        
      })

Haven't come up with anything else yet. The array is new with the desired values, everything is ok with this. But how to change the order values ​​in the database - I have no idea, in fact, this is the question.
I will be glad to any useful comments, since I am new to backing and, in fact, this is my first more or less serious experience with mongoose.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question