res.json()创建CastError

时间:2019-04-11 13:40:02

标签: javascript node.js express backend

在将res.json()与参数一起使用时,会导致CastError: CastError:模型“ Post”的路径“ _id”的值“ undefined”的强制转换为ObjectId失败

如果我仅使用不带参数的rest.status(),res.sendStatus()或res.json(),则不会出现问题。

exports.createPost = async (req, res, next) => {
  try {
    errorsIsEmpty(validationResult(req));
    const { communityId } = req.params;
    const { type } = req.query;
    const { title, content } = req.body;
    const user = await User.findById(req.userId)
    const community = await Community.findById(communityId);
    const banned = await community.authorized(req.userId)
    if(banned){
      ////// This line causes the problem //////
     return res.status(403).json({})
    }
    else {
      let post;
      if (type === 'text') {
      post = new Post({
        title,
        content,
        authorId: req.userId,
      });
    } else if (type === 'image') {
      if (!req.file) {
        const error = new Error('No image provided.');
        error.statusCode = 422;
        throw error;
      }
      const imageUrl = req.file.path;
      post = new Post({
        title,
        imageUrl,
        authorId: req.userId,
      });
    }
    await post.save();
  ////// This line works//////
    res.status(201).json({ postId: post._id });
    }
    
  } catch (err) {
    console.log(err);
    next(err);
    // errorFunc(err, next);
  }
};

模型“ Post”的路径“ _id”处的

r值“ undefined”

1 个答案:

答案 0 :(得分:0)

您的_id是一个字符串,但必须是ObjectId类型。我以为你在用猫鼬。您需要导入/需要猫鼬,然后将_id值包装在ObjectId

const mongoose = require('mongoose');

const ObjectId = mongoose.Types.ObjectId;

// in your route handler
  await post.save();
  ////// This line works//////
  res.status(201).json({ postId: ObjectId(post._id) });