为什么我在发送网络请求时在 mongodb 上收到 'Cast to ObjectId failed for value' 错误?

why do i get 'Cast to ObjectId failed for value' error on mongodb while sending network request?

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

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

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

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;

这是我的用户数据库记录

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

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