【问题标题】:Creating a relationship between models with additional info in Mongo, Express, Node在 Mongo、Express、Node 中使用附加信息创建模型之间的关系
【发布时间】:2021-04-24 15:40:30
【问题描述】:

对 Node 有点陌生,一直在为这种模型关系而苦苦挣扎,在这里找不到答案。

我试图在四个模型之间建立关系:

  1. 用户
  2. 审核
  3. 主题
  4. 课程

当用户对某个主题的课程发表评论时,我想跟踪用户模型上的“主题分数”。

因此,如果用户查看了编程课程,他们的编程主题分数应该会得到 +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


    【解决方案1】:

    好吧,经过一番折腾,我终于弄明白了。

    用户模型保持不变:

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

    }]

    然后让代码在他们发表评论时增加他们在每个主题上的分数:

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

    丑陋而不优雅,但它可以完成工作。

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 2016-06-14
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      相关资源
      最近更新 更多