簡體   English   中英

在貓鼬中更新數組內的文檔

[英]updating document inside array in mongoose

我想在答案數組中更新我的答案對象。 我正在使用以下架構

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const questionSchema = new mongoose.Schema(
  {
    postedBy: {
      type: ObjectId,
      required: true,
      ref: "User",
    },
    question: {
      type: String,
      required: true,
    },
    photo: {
      data: String,
      required: false,
    },
    answers: [
      {
        userId: { type: ObjectId, ref: "User" },
        answer: String,
      },
    ],
    questionType: {
      data: String,
      required: false,
    },
  },

  { timeStamps: true }
);

module.exports = mongoose.model("Question", questionSchema);

我正在使用 updateOne 方法來更新我的數據庫中的答案。 任何人都可以解釋這里缺少什么。 幾個小時以來我一直在努力解決這個問題

exports.updateAnswer = (req, res) => {
  const questionId = req.body.questionId;
  const answerId = req.body.answerId;

  Question.findOne({ _id: questionId }).exec((err, question) => {
    if (err) {
      res.status(400).json({
        error: errorHandler(err),
      });
      return;
    }
    if (!question) {
      res.status(400).json({
        error: "question not found",
      });
      return;
    }
  });

  Question.updateOne(
    { _id: answerId },
    {
      $set: {
        "answers.$.answer": "This is update answer. My name is Ravi Dubey",
      },
    },
    { new: true },
    (err, success) => {
      if (err) {
        res.status(400).json({
          error: errorHandler(err),
        });
      }
      res.json({
        msg: "answer updated successfully",
        success,
      });
    }
  );
};

我的結果是成功的,但答案沒有在數據庫中更新。 我對 Question.updateOne 方法感到困惑。 任何幫助表示贊賞。

如果您嘗試根據answers數組中文檔之一的id進行查詢,那么您需要提供{'answers._id': answerId}而不是{_id: answerId} {'answers._id': answerId} 而且,如果您需要更新的文檔作為結果,那么您應該使用findOneAndUpdate方法。

Question.findOneAndUpdate(
  { "answers._id": answerId },
  { $set: { "answers.$.answer": "some answer" } },
  { new: true },
  (err, data) => {
    // handle response
  }
);

暫無
暫無

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

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