簡體   English   中英

Mongoose -> 從自定義 Schema 方法更新文檔

[英]Mongoose -> Updating document from custom Schema method

我嘗試做的是從自定義架構函數中更新數組。

我有一個基於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因為我會視做一些更多的操作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

有誰知道如何做到這一點? 我找不到解決方案。

任何幫助將不勝感激!

對於發現此問題的任何其他人,解決方案與嵌套的更新對象有關,因此默認情況下不會檢測到更改。 在這種情況下的解決方案是調用

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

這應該將更改傳播到數據庫。 該功能記錄在此處https://mongoosejs.com/docs/schematypes.html#mixed

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM