簡體   English   中英

在 MongoDB 中保存數組字段

[英]Saving array field in MongoDB

伙計們-我正在嘗試在 MongoDB 中保存一個數組字段,但它不想正確保存。

我正在嘗試構建一個瑣事托管應用程序。 所討論的 API 端點將允許主機獲取在一輪中為每個問題收到的每個響應,並確定它是否應該獲得全分、不計分或介於兩者之間。 我的圓形文檔如下所示:

{
    "_id":{"$oid":"6067c6c7c1821e3db0530eb9"},
    "type":"general",
    "game ":{"$oid":"6067c666c1821e3db0530eb7"},
    "questions":[
        {
            "text":"What is the capital of Finland?",
            "answer":"Helsinki",
            "value":2,
            "key":[],
            "number":1
        },
        {
            "text":"What is the capital of Kazakhstan?",
            "answer":"Nursultan",
            "value":2,
            "key":[],
            "number":2
        }
    ],
    "title":"My test round",
    "description":"This describes my test round.",
    "settings":{
        "endBonus":false,
        "maxWager":0,
        "releaseQuestions":false,
        "answerAfterEach":false
    },
    "owner":{"$oid":"605271517fce7249cc8eb436"},
    "__v":3
}

req.body 看起來像這樣:

{
    "key": [
        {
            "answer":"Helsinki",
            "key":[
                {
                    "answer":"helsinki",
                    "correct": 1
                }
            ]
        },
        {
            "answer":"Nursultan",
            "key":[
                {
                    "answer":"nursultan",
                    "correct": 1
                },
                {
                    "answer":"nur-sultan",
                    "correct": 1
                },
                {
                    "answer":"astana",
                    "correct": 0.5
                }
            ]
        }
    ]
}

這是為每個問題更新密鑰的代碼:

exports.gradeRound = catchAsync(async (req, res, next) => {
  const r = await Round.findById(req.params.rid);
  //for each question in the round
  let newKey;
  for (var i = 0; i < r.questions.length; i++) {
    console.log(`Question ${i + 1} info:`);
    console.log(r.questions[i]);
    console.log();

    console.log(`Key ${i + 1}:`);
    console.log(req.body.key[i].key);
    console.log();

    // ...some deleted code that verifies that the correct question
    // ...is being graded...that part works fine.

    // copy the array from req.body and set the key array for the question
    // The code commented below are other ways I've tried to set the array.

    // req.body.key[i].key.forEach((a) => {
    //   r.questions[i].key.push(a);
    // });

    // r.questions[i].key = req.body.key[i].key;

    newKey = req.body.key[i].key.slice();
    newKey.forEach((el) => {
      r.questions[i].key.push({ ...el });
      console.log(r.questions[i].key);
    });
  }

  const ans = await r.save();

  // this logged the document with empty keys for each question.
  // const newR = await Round.findById(req.params.rid);
  // console.log(newR);

  // ...yet this gave what I would have expected for ans...the round with the 
  // keys populated
  res.status(200).json({
    status: 'success',
    data: ans,
  });
});

有趣的是,每個 console.log 都給了我我所期望的。 響應回來了我所期望的 - “ans” object 中的關鍵 arrays 填充了來自 req.body 的確切值。 但是,當我再次查詢數據時(從 r.save() 下方注釋掉的代碼中可以看到),沒有填充任何鍵,當我查看 MongoDBCompass 時也是如此。

我在這里拉頭發-我做錯了什么? 還是我遺漏了一些小細節?

更新 -

顯然,Mongoose 看起來不夠深入,無法看到該數組字段已更改(因為它嵌入在主文檔的數組中的 object 中),所以為了強制它保存,我在 Z4B43B0AEE35624CD95BZsave018 正上方添加了這一行():

r.markModified('questions');

然后,當我這樣做

const ans = await r.save();

...它看到“問題”被修改並保存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM