简体   繁体   English

在 Mongo、Express、Node 中使用附加信息创建模型之间的关系

[英]Creating a relationship between models with additional info in Mongo, Express, Node

somewhat new to Node and been struggling with this model relationship and not finding an answer here.对 Node 来说有点新,并且一直在努力处理这种 model 关系,但在这里找不到答案。

I have four models I'm trying to create relationships between:我有四个模型我试图在它们之间建立关系:

  1. User用户
  2. Review审查
  3. Topics话题
  4. Courses培训班

When a User leaves a Review on a Course in a certain Topic, I want to track a "topic score" on the User model.当用户对某个主题的课程发表评论时,我想跟踪用户 model 的“主题分数”。

So if a User Reviewed a programming Course, they should get +10 to their programming Topic score.因此,如果用户查看了编程课程,他们的编程主题分数应该会得到 +10。 Then I should be able to query User.scores.programming to get their Programming score.然后我应该能够查询 User.scores.programming 以获得他们的编程分数。

The Reviews are being created fine, it's just the Topic scoring part where I'm running into issues.评论创建得很好,这只是我遇到问题的主题评分部分。

Here's how my User schema are set up, just the relevant part:这是我的用户模式的设置方式,只是相关部分:

const userSchema = new mongoose.Schema({
...
  scores: [{
    topic: {
      type: mongoose.Schema.ObjectId,
      ref: 'Topic'
    },
    score: {
      type: Number,
      default: 0
    }
  }]
});

And here's the code I have so far right now for trying to increment the score:这是我目前尝试增加分数的代码:

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
      
    }
  }
}

I know I probably have a few different things wrong here, and I've been very stuck on making progress.我知道我在这里可能有一些不同的问题,而且我一直非常坚持取得进展。 Any pointers or examples I can look at would be extremely helpful!我可以查看的任何指针或示例都会非常有帮助!

Alright so after lots of messing around I eventually figured it out.好吧,经过一番折腾,我终于弄明白了。

User model stayed the same:用户 model 保持不变:

scores: [{
topic: {
  type: mongoose.Schema.ObjectId,
  ref: 'Tag'
},
score: {
  type: Number,
  default: 0
}

}] }]

Then for the code to increment their score on each topic when they leave a review:然后让代码在他们留下评论时增加他们在每个主题上的分数:

const updateUserScores = async (userId, course) => {
  const user = await User.findOne({_id: userId}).populate({
    path    : 'scores',
    populate: [
        { path: 'topic' }
    ]
  });
  let userScores = user.scores;
  userScores = userScores.map(x => x.topic._id);
  let topics = await Course.findOne({_id: course}).populate('tags');
  topics = topics.tags.map(x => x._id);
  for (t of topics) {
    const operator = userScores.includes(t) ? true : false;
    if (!operator) {
      const userScoring = await User
        .findByIdAndUpdate(userId, 
            { $addToSet: { scores: {topic: t, score: 10}}},
            { new: true}
        );
    } else {
      const currentScore = await user.scores.find(o => o.topic._id == `${t}`);
      
      const userScoring = await User
        .findByIdAndUpdate(userId,
          { $pull: { scores: {_id: currentScore._id}}},
          { new: true }
        )
      const userReScoring = await User
        .findByIdAndUpdate(userId,
          { $addToSet: { scores: {topic: t, score: (currentScore.score + 10)}}},
          { new: true }
        )
    }
  }
}

Ugly and not super elegant, but it gets the job done.丑陋而不是超级优雅,但它完成了工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM