V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
leebs
V2EX  ›  MongoDB

Mongodb 字符串转 ObjectId

  •  
  •   leebs · Dec 23, 2021 · 2907 views
    This topic created in 1594 days ago, the information mentioned may be changed or developed.

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

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

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

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

    5 replies    2021-12-24 10:34:08 +08:00
    Weny
        1
    Weny  
       Dec 23, 2021 via iPhone
    check here
    leebs
        3
    leebs  
    OP
       Dec 24, 2021
    @Weny 这个只是介绍了下 ObjectId 是啥吧。。
    edward1987
        4
    edward1987  
       Dec 24, 2021
    mongoose Schema 里面直接定义字段类型为 `mongoose.Types.ObjectId`
    Weny
        5
    Weny  
       Dec 24, 2021
    @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>" }
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   993 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 23:18 · PVG 07:18 · LAX 16:18 · JFK 19:18
    ♥ Do have faith in what you're doing.