首页 > 解决方案 > Mongoose -> 从自定义 Schema 方法更新文档

问题描述

我尝试做的是从自定义模式函数中更新数组。

我有一个User基于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

在服务器上我只是调用函数:

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 ) )

日志按计划向我显示了正确数组中的新时隙,但是当我再次运行该函数或在数据库中检查时隙时,它没有保存。

我想这样做而不是使用,因为稍后我将根据函数中的findOneAndUpdate内容进行更多操作。this.schedulesaveTimeslot

我尝试了以下工作正常:

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

有谁知道如何做到这一点?我找不到解决方案。

任何帮助将不胜感激!

标签: javascriptmongodbmongoosemethodsschema

解决方案


对于发现此问题的其他任何人,该解决方案与嵌套的更新对象有关,因此默认情况下不会检测到更改。在这种情况下的解决方案是调用

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

这应该将更改传播到数据库。该功能记录在这里https://mongoosejs.com/docs/schematypes.html#mixed


推荐阅读