【问题标题】:How can I cast ObjectId in Mongodb? I have tried different ways but still getting errors如何在 Mongodb 中转换 ObjectId?我尝试了不同的方法,但仍然出现错误
【发布时间】:2020-06-21 03:51:50
【问题描述】:

架构

//架构设置

var campgroundSchema = new mongoose.Schema({
    name: String,
    image: String,
    description: String
})

var campground = mongoose.model("campground", campgroundSchema)


#The error is where coming from here, don't seem to get the campgrounds diplayed
app.get("/campgrounds/:id", function(req, res){
    //find the campground with provided ID
    campground.findById(req.params.id, function(err, foundCampground){
        if(err){
            console.log(err)
        } else {
            //render show template
            res.render("show", {campground: foundCampground})
        }
    })
})
    

错误信息

** 消息: '在模型“campground”的路径“_id”处,值“5e61150b58e80830240ef790”转换为 ObjectId 失败', 名称:'CastError', 模型:模型{露营地}}**

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

当您创建这样的架构时,您可以传递{ _id: false }

var campgroundSchema = new mongoose.Schema({
    name: String,
    image: String,
    description: String
}, { _id: false })

【讨论】:

  • Modie 我试过了,我得到了以下错误~ |

    2| 3| 4|无法读取 null 的属性“名称”
  • 那一定是您模板中的其他内容。我想它解决了你原来的问题。看起来 foundCampground 要么是空的,要么是没有被通过。
  • 为什么要更改模式中的某些内容以进行读取? { _id: false } 也可以帮助您避免自动创建 _id 但与投射错误无关!!
【解决方案2】:

您可以使用mongoose.Types.ObjectId() 方法将您的字符串转换为MongoId,并将您的字符串作为第一个参数传递。

例如,使用上述方法后,您的代码如下所示

app.get("/campgrounds/:id", function(req, res){
    //find the campground with provided ID
    campground.findById(
      mongoose.Types.ObjectId(req.params.id),
      function(err, foundCampground){
        if(err){
            console.log(err)
        } else {
            //render show template
            res.render("show", {campground: foundCampground})
        }
    })
});

【讨论】:

  • 我试过了,得到了这个错误 - 错误:传入的参数必须是 12 个字节的单个字符串或 24 个十六进制字符的字符串
  • 您不需要使用mongoose.Types.ObjectId() 将字符串转换为ObjectId(),因为.findById() 接受字符串并在内部进行转换!!
  • 哦,那么 @JamoniJamo 必须将错误的字符串传递给 findById() 方法。 @JamoniJamo 在调用 findById() 方法之前,您是否尝试过记录字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2021-03-21
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
相关资源
最近更新 更多