如何解决为什么在发送网络请求时在 mongodb 上出现“Cast to ObjectId failed for value”错误?
我正在尝试制作一个社交网站,我想在其中集成关注者建议。所以我已经向后端发送了一个包含用户 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);
})
);
但是每当我从邮递员发送请求时,我都会收到此错误
{
"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,emailAddress: { type: String,password: { type: String,following: [{ type: mongoose.Schema.Types.ObjectId,required: true }],followers: [{ type: mongoose.Schema.Types.ObjectId,},{
timestamps: true,}
);
const User = mongoose.model("User",userSchema);
export default User;
这是我的用户数据库记录 this question
解决方法
看来您正在尝试检查它是否不在一组 id 中,因此您应该使用 $nin
(not in) 而不是 $ne
(not equal)
_id: { $nin: req.body.following },
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。