使用自己的字段更新 MongoDB 文档
我正在尝试为我的 mongodb 文档创建一个受欢迎程度索引字段,如下所示:
popularityIndex: {
type: Number,
default: function() {
return this.views.count * 0.3 + this.upVoted.count * 0.3 - this.downVoted.count * 0.1 - ((new Date().getTime() - this.creationDate.getTime())) * 0.2
},
},
我想知道是否有一种方法可以在它依赖的字段之一更新时更新此字段,同时保持原子性,或者在更新时获取字段,像这样:
await Model.updateOne({ _id }, {
$set: { popularityIndex: 'views.count' * 0.3 + 'upVoted.count' * 0.3 - 'downVoted.count' * 0.1 - ((new Date().getTime() - 'creationDate'.getTime()) / 10000000) * 0.2 }
})
这些是我需要更新的字段,最后一个是要更新的字段:
{
"upVoted": {
"count": "2"
},
"downVoted": {
"count": "3"
},
"views": {
"count": "5"
},
"creationDate": "2022-04-11T16:02:39.956+00:00",
"popularityIndex": "1.453"
}
因此,如果文档收到赞成票,我也必须更新流行度索引:
await Model.updateOne({ _id }, {
$inc: { 'upVoted.count': 1 }
}
await Model.updateOne({ _id }, {
$set: { popularityIndex: this.views.count * 0.3 + this.upVoted.count * 0.3 - this.downVoted.count * 0.2 - ((new Date().getTime() - this.creationDate.getTime())) * 0.2 }
}) // <-- this is the part I don't know
I'm trying to make a popularityIndex field for my mongodb documents like this:
popularityIndex: {
type: Number,
default: function() {
return this.views.count * 0.3 + this.upVoted.count * 0.3 - this.downVoted.count * 0.1 - ((new Date().getTime() - this.creationDate.getTime())) * 0.2
},
},
I was wondering if there is a way to update this field whenever one of the fields it depends on gets update, while keeping the atomicity, or getting the fields when updating, something like this:
await Model.updateOne({ _id }, {
$set: { popularityIndex: 'views.count' * 0.3 + 'upVoted.count' * 0.3 - 'downVoted.count' * 0.1 - ((new Date().getTime() - 'creationDate'.getTime()) / 10000000) * 0.2 }
})
These are the fields that I need for updating and the last one is the one that gets updated:
{
"upVoted": {
"count": "2"
},
"downVoted": {
"count": "3"
},
"views": {
"count": "5"
},
"creationDate": "2022-04-11T16:02:39.956+00:00",
"popularityIndex": "1.453"
}
So if the document receives an upvote, I'll have to update the popularity index too:
await Model.updateOne({ _id }, {
$inc: { 'upVoted.count': 1 }
}
await Model.updateOne({ _id }, {
$set: { popularityIndex: this.views.count * 0.3 + this.upVoted.count * 0.3 - this.downVoted.count * 0.2 - ((new Date().getTime() - this.creationDate.getTime())) * 0.2 }
}) // <-- this is the part I don't know
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许像这样
Mongo Playground
Maybe like this
Mongo Playground