Node.js 在MongoDB中保存数组字段

Node.js 在MongoDB中保存数组字段,node.js,mongodb,mongoose,mongodb-query,Node.js,Mongodb,Mongoose,Mongodb Query,各位-我试图在MongoDB中保存一个数组字段,但它不想正确保存 我正在尝试建立一个琐事托管应用程序。有问题的API端点将允许主机在一轮中对每个问题接收到的每个响应进行记录,并确定是否应该获得全额积分、无积分或介于两者之间的某个积分。我的圆形文档如下所示: { "_id":{"$oid":"6067c6c7c1821e3db0530eb9"}, "type":"general",

各位-我试图在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
}
{
    "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
                }
            ]
        }
    ]
}
req.body如下所示:

{
    "_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
}
{
    "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,
  });
});
exports.gradeRound=catchAsync(异步(请求、恢复、下一步)=>{ const r=wait Round.findById(请求参数rid); //对每一个问题进行全面的讨论 让纽基; 对于(var i=0;i{ //r.问题[i].键.推(a); // }); //r.questions[i].key=req.body.key[i].key; newKey=req.body.key[i].key.slice(); newKey.forEach((el)=>{ r、 问题[i].key.push({…el}); log(r.questions[i].key); }); } const ans=等待r.save(); //这会记录文档,每个问题都有空键。 //const newR=wait Round.findById(req.params.rid); //控制台日志(newR); //…然而这给了我对ans的期望…一轮 //已填充的密钥 res.status(200).json({ 状态:“成功”, 数据:ans, }); }); 有趣的是,每个console.log都给了我我所期望的。响应返回了我所期望的结果——“ans”对象中的键数组填充了req.body中的精确值。但是,当我再次查询数据时(从r.save()下面注释掉的代码中可以看到),没有任何键被填充,我在MongoDBCompass中查看时也是这样

我在这里发牢骚——我做错了什么?还是我遗漏了一些小细节?

更新-

很明显,Mongoose没有深入查看数组字段是否已更改(因为它嵌入了主文档中数组中的对象中),因此为了强制保存,我在r.save()的正上方添加了这一行:

然后,当我

const ans = await r.save();
…它看到“问题”被修改并保存