[英]MongoDB extended json to update objectid
I am trying to update ObjectId using mongodb extended json .我正在尝试使用mongodb 扩展 json更新 ObjectId 。
I am using the below to insert the document.我正在使用以下内容插入文档。
collection.insertMany([{ parentQueryGroupId: { $oid :
"628fadb4d370987ac789c0cd" } }])
So it is storing as is like parentQueryGroupId: { $oid : "628fadb4d370987ac789c0cd"
.所以它就像
parentQueryGroupId: { $oid : "628fadb4d370987ac789c0cd"
一样存储。
But as I need it to store as ObjectId("628fadb4d370987ac789c0cd")
但因为我需要它存储为
ObjectId("628fadb4d370987ac789c0cd")
Is this possible directly through extended JSON?这可以直接通过扩展 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.
所以我从客户端发送数据,然后直接传递该 id 进行更新。 But I need it to be ObjectId instead of an object.
但我需要它是 ObjectId 而不是对象。
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?如果存在
$oid
键,我可以在这种情况下循环,然后我可以将其转换为ObjectId
,但是 Mongoose 或 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.我使用
bson
包中的EJSON
将其转换为适当的格式,如下所示。
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.如果它不是扩展的 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).在没有扩展类型的情况下也能很好地工作(除非你真的想按原样存储这些
$oid
格式,因为反序列化也会转换它们)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.