【发布时间】: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