当前位置: 首页 > 知识库问答 >
问题:

如何在Mongodb中转换ObjectId?我尝试过不同的方法,但仍然会出错

邹高峻
2023-03-14

//模式设置

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})
        }
    })
})
    

**消息:“转换为ObjectId失败,因为模型“CampGrand”的路径“_id”处的值“5e61150b58e80830240ef790”,名称:“CastError”,模型:模型{CampGrand}**

共有2个答案

邵劲
2023-03-14

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

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

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})
        }
    })
});
戚默
2023-03-14

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

var campgroundSchema = new mongoose.Schema({
    name: String,
    image: String,
    description: String
}, { _id: false })
 类似资料:
  • 本文向大家介绍python将MongoDB里的ObjectId转换为时间戳的方法,包括了python将MongoDB里的ObjectId转换为时间戳的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了python将MongoDB里的ObjectId转换为时间戳的方法。分享给大家供大家参考。具体分析如下: MongoDB里的_id字段前四位是时间戳的16进制表示,通过Python可以很容易

  • 问题内容: 我有一个ConcurrentMap,它在我的可运行对象外部实例化,但是在/跨整个可运行对象内部共享和更新。我的可运行对象需要是并发的,但是我的currentMap的更新需要同步,以防止替换先前的条目。有人可以告诉我我在做什么错。 可运行 结果 -注意索引0被添加多次而不是一次。它应该由线程0添加,并由线程9读取。我不知何故需要将该方法与其他线程锁定,直到更新完成。 问题答案: 在方法上

  • 我匹配了所有的数据类型,但还是会出错 "不允许从数据类型'INT'到'CHAR'的隐式转换。使用CONVERT函数运行此查询。" 请导游。

  • 本文向大家介绍MongoDB查询以从ObjectId转换为String,包括了MongoDB查询以从ObjectId转换为String的使用技巧和注意事项,需要的朋友参考一下 在MongoDB中使用toString()将ObjectId转换为字符串。让我们创建一个包含文档的集合 在find方法的帮助下显示集合中的所有文档- 这将产生以下输出- 以下是将ObjectId转换为String的查询- 现

  • 我使用方法将一列字符串转换为datetime对象。 这给了我以下的错误- 回溯(最近一次调用):文件“/Users/pranavmarla/jama/lib/python3.6/site packages/pandas/core/tools/datetimes.py”,第448行,在类似于列表的日期时间值中,tz=conversion。datetime_to_datetime64(arg)文件“p

  • 任务:剪贴板_管理器:verifyReleaseResources'的执行失败。 执行com.android.build.gradle.internal.tasks.工人$ActionFacade Android资源链接失败时发生故障C:\用户\zraed.gradle\缓存\transforms-2\files-2.1\31ffd94dd4be5a0ccaa73c0d1aa53e0e\core-