javascript - 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.schedule
saveTimeslot
我尝试了以下工作正常:
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
推荐阅读
- c# - 在 Nunit 中优先运行类
- node.js - 部署到 AWS 之前的设计注意事项?
- excel - Excel VBA粘贴图表与源图表不同
- python - 如何在python中使用八倍精度
- matlab - 有没有办法计算成对向量位移而不是使用嵌套的 for 循环?
- angular - Angular 2 绑定:附加到 src
- scala - Akka 演员抛出空指针错误,原因未知
- r - 以编程方式打印我正在工作的 Rproject 的名称
- coq - 什么是子目标“nat”
- amazon-web-services - 我可以将 nginx 放在公有子网上,将 webserver[s] 放在 AWS VPC 的私有子网上吗?