V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
leebs
V2EX  ›  MongoDB

Mongodb 字符串转 ObjectId

  •  
  •   leebs · 2021-12-23 23:39:21 +08:00 · 2106 次点击
    这是一个创建于 826 天前的主题,其中的信息可能已经有所发展或是发生改变。

    原 MongoDB 数据包含 ObjectId 类型的字段。

    构建缓存的时候,将 MongoDB 数据通过 JSON.srtingify 存储到 redis 中,这时候 ObjectId 类型的字段都会变为字符串。

    取缓存的时候,如果我要获取 ObjectId 类型的字段,就必须手动做类型转换。

    有其他办法可以根据 Schema 自动做类型转换嘛?或者 JSON.stringify 不转换 ObjectId 类型。

    5 条回复    2021-12-24 10:34:08 +08:00
    Weny
        1
    Weny  
       2021-12-23 23:49:13 +08:00 via iPhone
    check here
    Weny
        2
    Weny  
       2021-12-23 23:49:23 +08:00 via iPhone
    leebs
        3
    leebs  
    OP
       2021-12-24 00:04:16 +08:00
    @Weny 这个只是介绍了下 ObjectId 是啥吧。。
    edward1987
        4
    edward1987  
       2021-12-24 10:33:53 +08:00
    mongoose Schema 里面直接定义字段类型为 `mongoose.Types.ObjectId`
    Weny
        5
    Weny  
       2021-12-24 10:34:08 +08:00
    @leebs

    JSON can only directly represent a subset of the types supported by BSON. To preserve type information, MongoDB adds the following extensions to the JSON format.

    for ObjectID
    ```
    { "$oid": "<ObjectId bytes>" }
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3665 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 10:25 · PVG 18:25 · LAX 03:25 · JFK 06:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.