Mongoose CastError:尽管请求正文中的 _id 有效,但 Express 控制器中的值 {} 转换为 ObjectId 失败

问题描述 投票:0回答:1

在邮递员中:

GET http://localhost:3000/api/v1/article

身体:

{
"_id" : "659bd71fd17c285560041681"
}

回复:

 "message": "got it!",
    "article": {
        "date": "08-01-2024",
          .... full data ...

在状态管理器中:

  const _id = '659bd71fd17c285560041681'
    const response = await axios.get('http://localhost:3000/api/v1/article', {
      params: { _id }
    })

_id 是相同的 - 它是从数据库中的集合复制的。

CastError: Cast to ObjectId failed for value "{}" (type Object) at path "_id"
reason: 
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

就像是同一个ID。在邮递员中,我发送了一个 JSON,所以我尝试了:

  const _id = '659bd71fd17c285560041681'
    const _idAsJSON = JSON.stringify(_id)
    const response = await axios.get('http://localhost:3000/api/v1/article', {
      data: { _idAsJSON }
    })

 const _idAsJSON = JSON.stringify(_id)
    const response = await axios.get('http://localhost:3000/api/v1/article', {
      params: { _idAsJSON }
    })

const _id = '659bd71fd17c285560041681';
try {
  const response = await axios.get('http://localhost:3000/api/v1/article', {
    params: { _id }
  });

 const response = await axios.get('http://localhost:3000/api/v1/article', {
      data: { _id }
    })

但我仍然明白:

CastError: Cast to ObjectId failed for value "{}" (type Object) at path "_id" for model "Article"
reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

但是 _is 是从集合中复制的有效 ID。

controller.js代码:

exports.getArticleById = async (req, res) => {
  const id = req.body;
  try {
    const article = await Article.findById(id);

所以我检查了邮递员发来的ID:

{ _id: '659bd71fd17c285560041681' }

所以我切换到:

const idObj = { _id: '659bd71fd17c285560041681' }
  // getters
  const getArticleByID = async function () {
    const response = await axios.get('http://localhost:3000/api/v1/article', {
      data: { idObj }
    })

但没有帮助...

javascript mongodb mongoose
1个回答
0
投票

如果您使用

const _id = '659bd71fd17c285560041681'
const response = await axios.get('http://localhost:3000/api/v1/article', {
    params: { _id }
})

您应该使用

检索参数
exports.getArticleById = async (req, res) => {
  const { _id } = req.body;
  try {
    const article = await Article.findById(_id);
© www.soinside.com 2019 - 2024. All rights reserved.