我尝试做的是从自定义架构函数中更新数组。
我有一个基于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 ) )
日志在计划中向我显示了右数组中的新鲜时段,但是当我再次运行该功能或在db中检查时间段时,它没有保存。
我想这样做,而不是使用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
有人知道如何做到这一点吗?我找不到解决方案。
任何帮助将不胜感激!
给任何发现这个问题的人,该解决方案与要嵌套的更新对象有关,因此默认情况下未检测到更改。在这种情况下,解决方案是致电
this.markModified('schedule')
await this.save()
应该传播到DB的更改。该功能在此处记录在此处https://mongoosejs.com/docs/schematypes.html#mixed