【问题标题】:How to correctly link collections in MongoDB/Mongoose如何正确链接 MongoDB/Mongoose 中的集合
【发布时间】:2016-01-29 09:04:14
【问题描述】:

我目前正在开发一个 Questionbank,我想将测试结果链接到用户帐户。我是 noSQL 数据库结构的新手,我只是想从专家那里获得关于将结果链接到用户的最佳方式的意见。

我应该让 userSchema 引用用户特定的测试分数集合吗?或者只是使用“ref:”链接到全局测试分数集合中的键?

【问题讨论】:

    标签: mongodb mongoose mean-stack


    【解决方案1】:

    您应该将您需要的数据视为 JSON,将其他实体视为属性和属性数组。

    希望这段代码对你有帮助:

    问题:

    {
       "title" : "It's a title of question",
       "otherProperty" : Boolean,
       "created_by: {
          "name": "User Who Created Question",
          "otherProperty":0
       },
       "answers": [
          {"text":"Answer content", 
           "created_by": {
              "name":"User Who Answered Question
            }, 
           "otherProperty":False
          },
          {"text":"Answer content", 
           "created_by": {
              "name":"User Who Answered Question
            }, 
           "otherProperty":False
          },
          {"text":"Answer content", 
           "created_by": {
              "name":"User Who Answered Question
            }, 
           "otherProperty":False
          }
       ]
    }
    

    在代码方面,您应该阅读 mongoose 文档,但您通常会使用 Ref 键。像这样:

    var Schema = mongoose.Schema;
    
    var QuestionSchema = new Schema({
       title: {
          type: String,
          required: true
       },
       answers: [{
          type: Schema.Types.ObjectId,
          ref: 'Answer'
       }]
    })
    
    var Answer = new Schema({
       text: {
          type: String,
          required: true
       },
       created_by: {
          type: Schema.Types.ObjectId,
          ref: 'User'
       }
    })
    

    希望对你有帮助。

    更新:我刚刚更新了第一个示例的示例代码。

    【讨论】:

    • 谢谢@Furkan,但是以不同的方式呈现数据不是更好吗?这样您就可以使用一个单独的集合来保存所有测试的答案,并链接回问题? { "title" : "Test Category 1", "answered_by: { "name": "User Who Took the Test" }, "marksheet": [ {"text":"Answer content", "Question": "ObjectId", "Correct": True, } ] }
    猜你喜欢
    • 2020-05-27
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2021-05-21
    • 2023-01-10
    • 2021-07-10
    相关资源
    最近更新 更多