【发布时间】:2021-04-24 15:40:30
【问题描述】:
对 Node 有点陌生,一直在为这种模型关系而苦苦挣扎,在这里找不到答案。
我试图在四个模型之间建立关系:
- 用户
- 审核
- 主题
- 课程
当用户对某个主题的课程发表评论时,我想跟踪用户模型上的“主题分数”。
因此,如果用户查看了编程课程,他们的编程主题分数应该会得到 +10。然后我应该能够查询 User.scores.programming 以获得他们的编程分数。
评论创建得很好,这只是我遇到问题的主题评分部分。
这是我的用户架构的设置方式,只是相关部分:
const userSchema = new mongoose.Schema({
...
scores: [{
topic: {
type: mongoose.Schema.ObjectId,
ref: 'Topic'
},
score: {
type: Number,
default: 0
}
}]
});
这是我目前尝试增加分数的代码:
const updateUserScores = async (userId, course) => {
const user = await User.findOne({_id: userId}).populate('scores');
const userScores = user.scores;
let topics = await Course.findOne({_id: course}).populate('tags');
topics = topics.tags.map(x => x._id);
// I know it works for here to get the array of topics that they need to be scored on
// Then we need to go through each topic ID, see if they have a score for it...
// If they do, add 10 to that score. If not, add it and set it to 10
for (topic in topics) {
const operator = userScores.includes(topic) ? true : false;
if (!operator) {
// Add it to the set, this is not currently working right
const userScoring = await User
.findByIdAndUpdate(userId,
{ $addToSet: { scores: [topic, 10] }},
{ new: true}
)
} else {
// Get the score value, add 10 to it
}
}
}
我知道我在这里可能有一些不同的问题,而且我一直在努力取得进展。我可以查看的任何指针或示例都会非常有帮助!
【问题讨论】:
标签: node.js mongodb express model-view-controller