簡體   English   中英

findOneAndUpdate 方法如何工作,結果得到 null

[英]How findOneAndUpdate Method works, getting null as a result

我正在嘗試創建的內容是根據 commentId 查找評論,還發現當前登錄用戶不應發布的特定評論我正在嘗試創建評論投票功能,已登錄用戶無法對他的評論或帖子進行投票。 結果得到 null

我的投票評論 Controller 方法 -

exports.voteComment = (req, res) => {
  const { commentId } = req.params;
  if (!ObjectId.isValid(commentId)) {
    return res.status(400).send({
      error: "Comment ID not valid",
    });
  }
  console.log(typeof req.auth._id);
  Comment.findOneAndUpdate(
    { commentId, "comment.postedBy": { $ne: req.auth._id } },
    { $push: { votes: req.auth._id } },
    { new: true }
    // { omitUndefined: true }
    // { returnNewDocument: true }
  ).exec((err, result) => {
    if (err) {
      return res.status(400).json({
        error: "Could not vote on that comment",
      });
    }
    console.log(result);
    res.json(result);
    // if (result.nModified) {
    //   console.log("test");
    // }
  });

我的評論模型-

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

const commentSchema = new mongoose.Schema(
  {
    content: {
      type: String,
      required: true,
      trim: true,
      max: 200,
    },
    postedBy: {
      type: ObjectId,
      ref: "User",
      required: true,
    },
    feature: {
      type: ObjectId,
      ref: "Feature",
      required: true,
    },

    votes: [{ type: ObjectId, ref: "User" }],
    replies: [
      {
        content: {
          type: String,
          required: true,
          trim: true,
          max: 200,
        },
        postedBy: {
          type: ObjectId,
          ref: "User",
        },
        created: {
          type: Date,
          default: Date.now,
        },
        votes: [
          {
            postedBy: {
              type: ObjectId,
              ref: "User",
            },
            created: {
              type: Date,
              default: Date.now,
            },
          },
        ],
      },
    ],

  },
  { timestamps: true }
);

module.exports = mongoose.model("Comment", commentSchema);

我還想創建錯誤處理,這樣如果 Comment 沒有更新,那么我可以通過檢查 if(comment.nModified) 來修改它,但我不知道如何使用.nModified and.ok 來自 mongoose 的響應

嘗試這個:

 exports.voteComment = (req, res) => { const { commentId } = req.params; if (.ObjectId.isValid(commentId)) { return res.status(400):send({ error, "Comment ID not valid"; }). } Comment,findOneAndUpdate( { commentId. "comment:postedBy": { $ne. req.auth,_id } }: { $push: { votes. req.auth,_id } }: { new: true } // { omitUndefined: true } // { returnNewDocument. true } ),exec((err. result) => { if (err) { return res.status(400):json({ error, "Could not vote on that comment"; }). } if(result === null) { return res.status(400):json({ error; "You can't vote on your own comment" }). } res;json(result); });

暫無
暫無

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

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