Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose -> Updating document from custom Schema method

What I try to do is updating an array from within a custom schema function.

I have a model User based on a UserSchema:

userschema.js:

const UserSchema = mongoose.Schema( {
  firstName: String,
  lastName: String,
  schedule: {
    'type': Object,
    'default': {
      'mon': [],
      'tue': [],
      'wed': [],
      'thu': [],
      'fri': [],
      'sat': [],
      'son': []
    }
  }
} ) 

UserSchema.methods.saveTimeslot = async function( timeslot ) {

  const toSave = {
    'id': timeslot.id,
    'start': timeslot.start,
    'end': timeslot.end,
    'daily': timeslot.daily
  }

  this.schedule[ timeslot.day ].push( toSave )
  await this.save()
  return Promise.resolve()
}

const User = mongoose.model( 'User', UserSchema )

module.exports = User

On the server I just call the function:

server.js

// ------------
// Update user
// ------------
const user = await User.findOne( { '_id': decoded.id } )
await user.saveTimeslot( timeslot )
console.log('user saved: ', JSON.stringify( user, null, 2 ) )

The log shows me the fresh timeslot in the right array in schedule, but when I run the function again or check in the db for the timeslot it's not saved.

I want to do it like this instead of using findOneAndUpdate because I'll do some more operations depending on this.schedule in the saveTimeslot function later.

I tried the following which works fine:

userschema.js:

const UserSchema = mongoose.Schema( {
  bla: Number
} ) 

UserSchema.methods.saveTimeslot = async function( timeslot ) {
  this.bla = Math.random()
  await this.save()
  return Promise.resolve()
}

const User = mongoose.model( 'User', UserSchema )

module.exports = User

Has anyone an idea how this can be done? I can't find the solution.

Any help would be greatly appreciated!

like image 258
Getter Jetter Avatar asked Dec 08 '25 10:12

Getter Jetter


1 Answers

To anyone else who finds this question, the solution is related to the updated object being nested so the change is not detected by default. The solution in this case is to call

this.markModified('schedule')
await this.save()

which should propagate the changes to the DB. The feature is documented here https://mongoosejs.com/docs/schematypes.html#mixed

like image 159
owfm Avatar answered Dec 10 '25 00:12

owfm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!