【问题标题】:Mongoose duplicate key error with addToSet带有 addToSet 的 Mongoose 重复键错误
【发布时间】:2021-07-31 16:56:51
【问题描述】:

这是我的架构,应用程序是 Instagram 的克隆。 Likes 模式在那里,它引用了用户的唯一 id

为此,我正在使用 addToSet 但出现重复键错误。 下面是模式模型和查询实现。

const postSchema = new mongoose.Schema({
  caption: {
    type: String,
    required: true,
  },
  postUrl: {
    type: String,
    required: true,
  },
  likes: [{ type: ObjectId, ref: "User"}],
  comments: [
    {
      text: String,
      postedBy: { type: ObjectId, ref: "User" },
      time: { type: Date, default: Date.now },
    },
  ],
  postedBy: {
    type: ObjectId,
    ref: "User",
  },
  time: { type: Date, default: Date.now },
});

mongoose.model("Post", postSchema);

我收到了这个错误

{
    "operationTime": "6960585855740149761",
    "ok": 0,
    "code": 11000,
    "codeName": "DuplicateKey",
    "keyPattern": {
        "likes": 1
    },
    "keyValue": {
        "likes": "6093b5b628bce2002328eed8"
    },
    "$clusterTime": {
        "clusterTime": "6960585855740149761",
        "signature": {
            "hash": "+/RdCIov1VsbZ8tXqprjn4ca940=",
            "keyId": "6918360005028610050"
        }
    },
    "name": "MongoError"
}

我从前端发送的元素不在 Likes 数组中 还是会出现这个错误

这是查询实现

router.put("/like", requireLogin, async (req, res) => {
  try {
    const postData = await Post.findByIdAndUpdate(
      req.body.postId,
      {
        $addToSet: { likes: [req.user._id] }, //pushing in to array
                // { $addToSet: { locations: ["New York", "Texas", "Detroit"] } }
      }
    ).populate("postedBy", "_id name dpUrl");
    return res.json(postData);
  } catch (error) {
    console.log(error);
    res.json({ error });
  }
});

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mern


    【解决方案1】:

    因此,$addToSet 用于向数组添加值,除非该值已经存在,在这种情况下 $addToSet 对该数组不做任何事情,操作将失败。

    您似乎将相同的 userId 添加到数组中,因此您可能会收到错误。

    尝试改变:

    {
            $addToSet: { likes: req.user._id }, //pushing unique ID of the user
                    // { $addToSet: { locations: ["New York", "Texas", "Detroit"] } }
          }
    
    

    更多详情,请查看here

    【讨论】:

    • 不,我没有向数组添加相同的值。你给的解决方案我已经试过了。没用。我查看了官方文档,但没有帮助。
    • 但是我必须再做一个查询来检查数组中是否存在数据。 push 方法虽然有效。
    • 所以,我建议你检查你传递的数据。
    • 我做到了,正确的数据(即 req.user._id)正在传递给 Likes 数组。
    猜你喜欢
    • 2016-09-14
    • 2021-08-11
    • 2013-08-09
    • 2018-10-12
    • 2015-05-01
    • 2015-03-08
    • 2020-09-29
    相关资源
    最近更新 更多