【问题标题】:why do i get 'Cast to ObjectId failed for value' error on mongodb while sending network request?为什么我在发送网络请求时在 mongodb 上收到“Cast to ObjectId failed for value”错误?
【发布时间】:2021-07-29 04:01:26
【问题描述】:

我正在尝试制作一个社交网站,我想在其中整合关注者的建议。所以我已经使用一组用户 ID 向后端发送网络请求。

后端 request.body 包含这个数组"following": ["608b05477eeba243c5ac8bcb","608b05477eeba243c5ac8bcc"]

我想要数据库中的所有用户,除了 following 数组中的那些 id。我已经在我的后端写了这个查询

userRouter.post(
  "/suggestions",
  expressAsyncHandler(async (req, res) => {
    console.log(req.body.following);
    const suggestedUsers = await User.find({
      _id: { $ne: req.body.following },
    });

    res.send(suggestedUsers);
  })
);

但是每当我从 postman 发送请求时,我都会收到此错误

{
    "message": "Cast to ObjectId failed for value \"[ '608b05477eeba243c5ac8bcb', '608b05477eeba243c5ac8bcc' ]\" at path \"_id\" for model \"User\""
}

我的 userModel.js 看起来像这样

const userSchema = new mongoose.Schema(
  {
    username: { type: String, required: true },
    fullName: { type: String, required: true },
    emailAddress: { type: String, required: true },
    password: { type: String, required: true },
    following: [{ type: mongoose.Schema.Types.ObjectId, required: true }],
    followers: [{ type: mongoose.Schema.Types.ObjectId, required: true }],
  },
  {
    timestamps: true,
  }
);

const User = mongoose.model("User", userSchema);

export default User;

这是我的用户数据库记录

【问题讨论】:

    标签: mongodb mongoose mongodb-query social-networking mern


    【解决方案1】:

    您似乎正在尝试检查它是否不在 id 数组中,因此您应该使用 $nin(not in) 而不是 $ne (not equal)

    _id: { $nin: req.body.following },
    

    【讨论】:

      猜你喜欢
      • 2013-02-03
      • 2017-04-04
      • 2017-08-14
      • 2023-04-02
      • 2020-12-10
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多