skip to Main Content

I am trying to update ObjectId using mongodb extended json.

I am using the below to insert the document.

collection.insertMany([{ parentQueryGroupId: { $oid :
"628fadb4d370987ac789c0cd" } }])

So it is storing as is like parentQueryGroupId: { $oid : "628fadb4d370987ac789c0cd".

But as I need it to store as ObjectId("628fadb4d370987ac789c0cd")

Is this possible directly through extended JSON? Thing is, the server-side query is generic. So I am sending data from the client-side and then directly passing that id to update. But I need it to be ObjectId instead of an object.

I can loop over in such cases where if there is $oid key is present then I can convert it to ObjectId, but is this natively supported by Mongoose or MongoDB?

2

Answers


  1. Chosen as BEST ANSWER

    I used EJSON from bson package to convert it to the appropriate format as below.

    import { EJSON } from 'bson';
    
    collection.insertMany(EJSON.deserialize([{ parentQueryGroupId: { $oid :
    "628fadb4d370987ac789c0cd" } }]))
    
    console.log(EJSON.deserialize([{ parentQueryGroupId: { $oid :
    "628fadb4d370987ac789c0cd" } }])) // Outputs similar to: [{ parentQueryGroupId: ObjectId("628fadb4d370987ac789c0cd") }]
    

    And it is not having issues if it is not extended json. works well without extended types as well (unless you actually want to store those $oid format as is because deserialize will convert them too).


  2. you can try this,

    const mongoose = require('mongoose'); 
    const ObjectId = mongoose.Types.ObjectId;
    
    collection.insertMany([{ parentQueryGroupId: {ObjectId("628fadb4d370987ac789c0cd")} }])
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search