简体   繁体   中英

MongoDB extended json to update objectid

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?

you can try this,

const mongoose = require('mongoose'); 
const ObjectId = mongoose.Types.ObjectId;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM