【问题标题】:Mongoose -> Updating document from custom Schema methodMongoose -> 从自定义 Schema 方法更新文档
【发布时间】:2019-10-03 16:58:06
【问题描述】:

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

我有一个基于UserSchema 的模型User

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,因为稍后我将根据saveTimeslot 函数中的this.schedule 执行更多操作。

我尝试了以下方法,效果很好:

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

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

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript mongodb mongoose methods schema


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 2021-03-22
      • 2014-12-09
      • 2014-05-29
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多