السلام عليكم.
في المثال التالي.
// Post Schema
const PostSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
minlength: 2,
maxlength: 200,
},
description: {
type: String,
required: true,
trim: true,
minlength: 10,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
category: {
type: String,
required: true,
},
image: {
type: Object,
default: {
url: "",
publicId: null,
},
},
likes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
},
{
timestamps: true,
}
);
// Post Model
const Post = mongoose.model("Post", PostSchema);
الموجه
// /api/posts/:id
router.get('/:id', validateObjectId, getSinglePostCtr)
الطبقة الوسيطة
module.exports = (req, res, next) => {
if (!mongoose.Types.ObjectId.isValid(req.params.id)) {
return res.status(400).json({message: "Invalid Id"})
}
next()
}
الدالة
const getSinglePostCtr = asyncHandler(async (req, res) => {
const post = await Post.findById(req.params.id)
.populate("user", ["-password"]);
console.log(post)
if (!post) {
return res.status(404).json({ msg: "Post Not Found" })
}
res.status(200).json(post);
});
لماذا قيمة user تساوي null
شكرا على المساعدة