我正在做一个社交媒体项目,当我发送喜欢/不像POST请求时,我得到了这个
**CastError:在路径“_id”处为模型“POST”的值“6283\n”(类型字符串)强制转换为OBJECTID失败。(E:\social-media-app-mern\node_modules\mongoose\lib\query.js:4639:21)处的Query.exec(E:\social-media-app-mern\node_modules\mongoose\lib\query.js:4738:15)处的Query.Query。然后在ProcessTicksAndRejections处消息(节点:内部/进程/任务_队列:96:5){MessageFormat:未定义,字符串值:‘“6283\n”“,类型:’OBJECTID‘,值:’6283\n‘,路径:’_id‘,原因:BSONTypeError:传入的参数必须是12个字节的字符串、24个十六进制字符的字符串或新BSONTypeError(E:\social-media-app-mern\node_modules\bson\lib\error.js:41:28)位于新的对象ID(E:\social-media-app-mern\node_modules\bson\lib\objectid.js:66:23)的错误对象ID位于(E:\social-media-app-mern\node_modules\mongoose\lib\cast\objectid.js:25:12)的对象ID.cast(E:\social-media-app-mern\node_modules\mongoose\lib\schema\objectid.js:247:12)在对象Id.SchemaType.applySetters在对象Id.SchemaType._CastForQuery在对象Id.SchemaType.CastForQuery(E:(E:\social-media-app-mern\node_modules\mongoose\lib\schematype.js:1135:12)-(E:\social-media-app-mern\node_modules\mongoose\lib\schematype.js:1567:15)-app-mern\Node_MODULES\MOGOSE\LIB\SCHEMATYPE.js:1557:15)位于对象ID。架构类型.CastForQuery Package (E:\social-media-app-mern\node_modules\mongoose\lib\schematype.js:1534:20)at CAST(E:\social-media-app-mern\node_modules\mongoose\lib\cast.js:336:32)
At Model.Query.Query.cast(E:\social-media-app-mern\node_modules\mongoose\lib\query.js:5062:12),值类型:‘字符串’}**
路线:
const express = require("express");
const { createPost, likeAndUnlikePost } = require("../controllers/post");
const { isAuthenticated } = require("../middlewares/auth");
const router = express.Router();
router.route("/post/:id").get(isAuthenticated, likeAndUnlikePost);
module.exports = router;
型号:
const mongoose = require("mongoose");
const postSchema = new mongoose.Schema({
caption: String,
image: {
public_id: String,
url: String,
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
createdAt: {
type: Date,
default: Date.now,
},
likes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
comments: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
comment:{
type: String,
required: true,
}
},
],
});
module.exports = mongoose.model("Post", postSchema);
喜欢和不喜欢发帖:
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({
success: false,
message: "Post not found",
});
}
if (post.likes.includes(req.user._id)) {
const index = post.likes.indexOf(req.user._id);
post.likes.splice(index, 1);
await post.save();
return res.status(200).json({
success: true,
message: "Post Unliked",
});
} else {
post.likes.push(req.user._id);
await post.save();
return res.status(200).json({
success: true,
message: "Post Liked",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message,
});
console.error(error) }
};
2条答案
按热度按时间dwthyt8l1#
首先验证_id是否存在。然后尝试将字符串的_id转换为OBJECTID,如
kb5ga3dv2#
在代码中的某个地方,您将字符串值赋给了_id(类型为ObjectID)