【问题标题】:MongoDB: update a collection based on another collectionMongoDB:根据另一个集合更新一个集合
【发布时间】:2019-12-08 00:11:53
【问题描述】:

我有一个在线测验门户网站项目。这些是我的模型:

用户模型

const userSchema = new Schema({
  firstName: { type: String, required: true, maxlength: 15 },
  lastName: { type: String, required: true, maxlength: 15 },
  rank: Number
});

评分模型

const scoreSchema = new Schema({
  userId: ObjectId,
  quizId: ObjectId,
  marks: Number,
  answers: [{ type: Object }],
});

我想在每次将记录插入分数模型后更新我的用户模型。

不出所料,这是我的排名公式。

平均 = 总分 / 参加测验的总次数

我如何使用 MongoDB 或 Mongoose 实现这一点?

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    您可以使用猫鼬schema method。让我们看看如何。

    用户架构:

    const userSchema = new Schema({
           firstName: { type: String, required: true, maxlength: 15 },
           lastName: { type: String, required: true, maxlength: 15 },
           rank: Number
    });
    
    const User = mongoose.model('User', userSchema);
    

    分数架构:

    const scoreSchema = new Schema({
       userId: ObjectId,
       quizId: ObjectId,
       marks: Number,
       answers: [{ type: Object }],
    });
    
    // Add post save method on this schema
     scoreSchema.post('save', function (doc) {
       console.log('this fired after a document was saved');
       // doc.userId  is you user for this score so
      // rank:calculated_rank you formula here
       User.updateOne({_id:doc.userId} , {rank:calculated_rank}) 
     });
     // model 
     const Score = mongoose.model('Score', scoreSchema);
    

    因此,每当您在 score 架构上调用 save 时,都会触发 post('save'),您可以在此函数中更新 userSchema。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 2013-07-31
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多